<?php
	class Shepherd_MonitoringLocalizationController extends Sss_Controller_Shepherd
	{
		private $_menuName = 'Monitoring & Localization';

		public function init()
		{
			parent::init();
			$this->checkInstance();
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			if (!$userInformation->username) {
				$this->_redirect("/$handle/user/login");
			}
		}

		public function loginAction()
		{
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$this->_redirect("/$handle/user/login");
		}

		public function indexAction()
		{
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$this->_redirect("/$handle/monitoring-localization/floor-plan");
		}
		public function floorPlanAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$params = $this->_request->getParams();
			//Check permission
			if (Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_FlOOR_PLAN, Sss_Ultility_CommonViewParamater::SELECT, 'feature', 'action' ,$this->listRole(), true) != 1 && Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_FlOOR_PLAN, Sss_Ultility_CommonViewParamater::EDIT, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/monitoring-localization/graphs");
			} else {
				$hardwareTable = new Application_Model_Mapper_Hardware();
				$containerTable = new Shepherd_Model_Mapper_Container();
				$instanceTable  = new Application_Model_Mapper_Instance();
				$stockLocationTable = new Application_Model_Mapper_StockLocation();
				$salocdataTable = new Application_Model_Mapper_SalocData();
				$chartSessionTable = new Shepherd_Model_Mapper_ChartSession();
				$filterParam['floorplan'] = $this->getValueRequest('floorplan', $this->getRequest()->getParam('floorplan', Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);
				$filterParam['stocklocation'] = $this->getValueRequest('stocklocation', $this->getRequest()->getParam('stocklocation', Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::STOCK_LOCATION_SESSION);
				$instance = $instanceTable->getInstanceByHandle($handle);
				//Delete chart and graphs not in chartsession
				$chartSessionTable->deleteChartNotInChartSession($instance->instanceid);
				//Get session harware list
				$filterParam['room'] = $this->getValueRequest('room', $this->getRequest()->getParam('room', Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);
				$localization = new Zend_Session_Namespace(Sss_Ultility_SessionName::LOCALIZATION_SESSION_FLOORPLAN . $this->getCurrentHandle());

				//Get order, page, limit param
				$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD] = $this->getValueRequest(Sss_Ultility_CommonViewParamater::ORDERFIELD, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::ORDERFIELD, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);
				$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE]  = $this->getValueRequest(Sss_Ultility_CommonViewParamater::ORDERTYPE, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::ORDERTYPE, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);
				$filterParam[Sss_Ultility_CommonViewParamater::PAGE]       = $this->getValueRequest(Sss_Ultility_CommonViewParamater::PAGE, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::PAGE, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);

				//Get session room list
				$filterParam[Sss_Ultility_CommonViewParamater::ORDERFIELD1] = $this->getValueRequest(Sss_Ultility_CommonViewParamater::ORDERFIELD1, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::ORDERFIELD1, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);
				$filterParam[Sss_Ultility_CommonViewParamater::ORDERTYPE1]  = $this->getValueRequest(Sss_Ultility_CommonViewParamater::ORDERTYPE1, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::ORDERTYPE1, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);
				$filterParam[Sss_Ultility_CommonViewParamater::PAGE1]       = $this->getValueRequest(Sss_Ultility_CommonViewParamater::PAGE1, $this->getRequest()->getParam(Sss_Ultility_CommonViewParamater::PAGE1, Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);


				$roomInformationValue =  1;
				if (isset($params[Sss_Ultility_CommonViewParamater::ROOM_INFORMATION])) {
					$roomInformationValue  = $params[Sss_Ultility_CommonViewParamater::ROOM_INFORMATION];
				}
				$roomInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ROOM_INFORMATION_SESSION . $this->getCurrentHandle());
				if ($roomInformation->roominformation != null) {
					if ($roomInformation->roominformation != $roomInformationValue && $roomInformationValue != -1 && $roomInformationValue != null) {
						$roomInformation->roominformation = $roomInformationValue;
					}
				} else {
					$roomInformation->roominformation = $roomInformationValue;
				}
				$this->view->assign(Sss_Ultility_CommonViewParamater::ROOM_INFORMATION, $roomInformation->roominformation);

				$hardwareStatusInformationValue =  1;
				if (isset($params['hardwarestatus'])) {
					$hardwareStatusInformationValue  = $params['hardwarestatus'];
				}
				$hardwareStatusInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::HARDWARE_STATUS_SESSION . $this->getCurrentHandle());
				if ($hardwareStatusInformation->hardwareStatus != null) {
					if ($hardwareStatusInformation->hardwareStatus != $hardwareStatusInformationValue && $hardwareStatusInformationValue != -1 && $hardwareStatusInformationValue != null) {
						$hardwareStatusInformation->hardwareStatus = $hardwareStatusInformationValue;
					}
				} else {
					$hardwareStatusInformation->hardwareStatus = $hardwareStatusInformationValue;
				}
				$this->view->assign(Sss_Ultility_CommonViewParamater::HARDWARE_STATUS_INFORMATION, $hardwareStatusInformation->hardwareStatus);

				//Get stocklocation for instance
				$stockLocations = $stockLocationTable->getLocationByInstance($instance->instanceid);
				$this->view->assign(Sss_Ultility_CommonViewParamater::STOCKLOCATIONS, $stockLocations);
				$stockLocation = $stockLocationTable->getLocationByInstance($instance->instanceid, true);

				//Process display data
				if(is_null($filterParam['stocklocation']) || $filterParam['stocklocation'] == Sss_Ultility_CommonViewParamater::UNDERFINE){
					foreach($stockLocation as $t){
						$filterParam['stocklocation'] = $t['stocklocation'];
					}
				}
				$stockLocationId = $filterParam['stocklocation'];

				if ((int) $filterParam['room']) {
					$strInfoContainer = $containerTable->getContainer($filterParam['room'], null, null, 1);
					$this->view->assign('compressor', $strInfoContainer->compressor);
					$this->view->assign('compressor_type', $strInfoContainer->compressor_type);
					$this->view->assign('lastest_revision', $strInfoContainer->lastest_revision);
					$this->view->assign('room_value', $strInfoContainer->room_value);
					$this->view->assign('isolation_material', $strInfoContainer->isolation_material);
					$this->view->assign('roomstatistic', $this->getRoomStatisticInformation($filterParam['room']));
				}

				//Get sensor list by room
				$hardwareByRoom = $hardwareTable->getHardwareByDestination("", Sss_Ultility_SystemName::ROOMS);
				$chartsByRoom = array();
				foreach ($hardwareByRoom as $tmp) {
					$chartsByRoom[$tmp['hardwareid']][$tmp['typename']][] = $tmp['chart'];
				}
				$this->view->assign(Sss_Ultility_CommonViewParamater::HARDWARE_BY_ROOM, $chartsByRoom);

				//Get dropdownlist floor plan
				if (is_null($stockLocationId)) {
					$floorplans = $containerTable->getFloorplanByStockLocation(0);
				} else { 
					$floorplans = $containerTable->getFloorplanByStockLocation(0,$stockLocationId);
				}

				$arrFloorplans = array();
				$this->view->assign('stocklocation', $stockLocationId);
				if (count($floorplans) > 0) {
					foreach($floorplans as $f) {
						$arrFloorplans[] =  $f['containerid'];
					}
				} else {
					$arrFloorplans[] = 0;
				}
				if (count($arrFloorplans) > 0) {
					if (!in_array($filterParam['floorplan'],$arrFloorplans)) {
						$filterParam['floorplan'] = $arrFloorplans[0];
					}
				}

				//Get dropdownlist room
				if ((int) $filterParam['floorplan']) {
					$floorid = $filterParam['floorplan'];
				} else {
					$floorid = -1;
				}
				$strContainer = null;
				$strContainerRoom = null;
				if (isset($params[Sss_Ultility_CommonViewParamater::ISSUBMIT])) {
					$isSubmit = (bool) $params[Sss_Ultility_CommonViewParamater::ISSUBMIT]; 
				} else {
					$isSubmit = null;
				}
				if ($isSubmit) {
					$filterParam['room'] = 0;
				}

				if ($filterParam['room'] != 0 ) {
					$strContainer = $containerTable->getContainer($filterParam['room'], $instance->instanceid, $stockLocationId, 1);
					$strContainerRoom = $containerTable->getContainer($filterParam['room'], $instance->instanceid, $stockLocationId, 1);
				} elseif ($floorid != -1) {
					$strContainer = $containerTable->getContainer($filterParam['floorplan'],$instance->instanceid, $stockLocationId, 0);
				}
				$strPhoto = ''; 
				if (!(int) $filterParam['floorplan']) {
					$filterParam['floorplan'] = isset($strContainer->containerid) ? $strContainer->containerid : 0;
					$strPhoto                 = '';
				}
				//Start saloc data is assign view  	
				$floorplanIdView = $filterParam['floorplan'];
				$getDataSalocView = $salocdataTable->getListSalocDataHardware($floorplanIdView);



				$this->view->assign(Sss_Ultility_CommonViewParamater::LOCALIZATION, $localization->localization);
				$this->view->assign(Sss_Ultility_CommonViewParamater::SALOC_HARDWARE,$getDataSalocView);
				$checkCoordinateError = Sss_Ultility_Common::convertCoordinatesToPixels();
				$this->view->assign(Sss_Ultility_CommonViewParamater::CHECK_CONFIGURATION, empty($checkCoordinateError) ? FALSE : TRUE);
				//End assign view

				if ($strContainer != null) {
					$strPhoto = $strContainer->photo;
				}
				if ($strContainerRoom != null) {
					$strPhoto = $strContainerRoom->photo;
				}
				//Get photofloorplan
				if ($strContainerRoom) {
					$photoFloorPlan = empty($strContainer->photofloorplan) ? $strContainerRoom->photofloorplan : $strContainer->photofloorplan;
				} elseif($strContainer) {
					$photoFloorPlan = $strContainer->photofloorplan;
				} else {
					$photoFloorPlan = '';
				}
				$iCount = 0; 
				$this->view->assign('photofloorplan', $photoFloorPlan);
				if (($strPhoto == '' || $strPhoto == null) && $filterParam['floorplan'] != 0 && $floorid != -1) {
					//Get hardware list
					$list       = $hardwareTable->getList($this->view->limit, 0, $filterParam, 'f');
					$row        = $list->list;
					$chartsByItem = array();
					$index = 0;
					foreach ($row as $tmp) {
						$chartIds = '';
						$chartList =    $hardwareTable->getChartIds($tmp['hardwareid']);
						if ($chartList) {
							foreach ($chartList as $c) {
								if($chartIds == '') {
									$chartIds = $c['chart'];
								} else {
									$chartIds = $chartIds . ',' .  $c['chart'];
								}
							}
						}
						$tmp['chart'] = $chartIds;
						if($tmp['valuetype'])
							$chartsByItem[$index]     = $tmp;
						$index = $index + 1;
					}
					$pagination = $list->pagination;
					$this->view->assign(Sss_Ultility_CommonViewParamater::FILTER_PARAM, $filterParam);
					$this->view->assign(Sss_Ultility_CommonViewParamater::ROW, $chartsByItem);
					$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION, $pagination);
				} else {
					if($filterParam['room'] != 0 && $filterParam['floorplan'] != 0 && $floorid != -1) {
						$arrHardware = array();
						$list       = $hardwareTable->getList($this->view->limit, 0, $filterParam, 'f');
						$row        = $list->list;
						$paginationHardware = $list->pagination;
						$count = 0;
						$iCount = 0;
						foreach ($row as $r) {
							$arrValueType = $hardwareTable->getlastValue($r['hardwareid'],$r['valuetype'], $instance->instanceid);
							if (count($arrValueType) > 0) {
								$valueType = $arrValueType[0];
								$createdDayMax = $arrValueType[1];
								$showValue = $arrValueType[3];
								$typeCode = $arrValueType[4];
							} else {
								$valueType = $arrValueType;
							} 
							$r[Sss_Ultility_CommonViewParamater::LAST_VALUE_HARDWARE] = $valueType;
							$chartList =    $hardwareTable->getChartIds($r['hardwareid'], $r['valuetype']);
							if($chartList){
								foreach($chartList as $c){
									if($chartIds == ''){
										$chartIds = $c['chart'];
									}else{
										$chartIds = $chartIds . ',' .  $c['chart'];
									}
								}
							} else {
								$chartIds = '';
							}
							$r['chart'] = $chartIds;
							$arrNetwork = array();
							$statusNetwork = false;
							if ($valueType) {
								$r[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_OFFLINE;
								if (Sss_Ultility_Common::checkHardwareOnline($createdDayMax)) {
									$r[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_ONLINE;
									$statusNetwork = true;
								}
								if (Sss_Ultility_Common::checkHardwareBadConnection($r['hardwareid'],$r['vendor'],$typeCode)) {
									$r[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_BAD_CONNECTION;
								}
								if (Sss_Ultility_Common::checkHardwareOfline($createdDayMax)) {
									$r[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_OFFLINE;
								}
								$r[Sss_Ultility_CommonViewParamater::CREATED_DATE_MAX] = $createdDayMax;
								$r[Sss_Ultility_CommonViewParamater::SHOW_VALUE] = $showValue;
								$arrHardware [$count] = $r;
								$iCount = $iCount + 1;
								$arrNetwork[$count][Sss_Ultility_CommonViewParamater::STATUS_NETWORK] = $statusNetwork;
								$arrNetwork[$count]['vendor'] = $r['vendor'];
								$arrNetwork[$count]['vendorname'] = $r['vendorname']; 
								$arrNetwork[$count]['stocklocation'] = $r['stocklocation'];

							}
							$count = $count + 1;
						}
						$arrStatusNetwork = Sss_Ultility_Common::getStatusNetwork($arrNetwork);
						if (isset($params[Sss_Ultility_CommonViewParamater::LIMIT_HARDWARE])) {
							$limitHardware = $params[Sss_Ultility_CommonViewParamater::LIMIT_HARDWARE];
						} else {
							$limitHardware = 0;  
						}
						$paginationHardware->limitHardware = $limitHardware;
						$this->view->assign(Sss_Ultility_CommonViewParamater::SENSORS, $arrHardware);
						$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION_HARDWARE, $paginationHardware);
						$this->view->assign(Sss_Ultility_CommonViewParamater::COUNT_PAGGING, $iCount); 
						$this->view->assign(Sss_Ultility_CommonViewParamater::STATUS_NETWORK, $arrStatusNetwork);
					}
					if ($strContainer) {
						$width = $strContainer->width;
						$height = $strContainer->height;
					} else {
						$width = '';
						$height = '';
					}
					$this->view->assign('photo', $strPhoto);
					$this->view->assign('width', $width);
					$this->view->assign('height', $height);
				}
				$rooms = $containerTable->getRoomByFloorplan($floorid);
				$filterParam['floorplan'] = $floorid;

				//Get room list
				$listRoom = $containerTable->getRoomList($this->view->limit, 0, $filterParam);
				$rowRoom        = $listRoom->list;
				$paginationRoom = $listRoom->pagination;
				$this->view->assign(Sss_Ultility_CommonViewParamater::ROW_ROOM, $rowRoom);
				$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION_ROOM, $paginationRoom);

				//Get hardware list
				$listSensor    = array();
				$arrNetwork = array();
				$statusNetwork = false;
				$netWork = array();
				try {
					foreach ((array) $rooms as $r) { 
						$arrHardware = array();
						$filterParam['containerid'] = $r['containerid'];
						$list       = $hardwareTable->getList($this->view->limit, 0, $filterParam, 'f');
						$row        = $list->list;
						if ($r) {
							$count = 0;
							$iCount = 0;
							foreach ($row as $h) {
								$arrValueType = $hardwareTable->getlastValue($h['hardwareid'],$h['valuetype'], $instance->instanceid);

								if (count($arrValueType) > 0) {
									$valueType = $arrValueType[0];
									$createdDayMax = $arrValueType[1];
									$showValue = $arrValueType[3];
									$typeCode = $arrValueType[4];
								} else {
									$valueType = $arrValueType;
								}
								$h[Sss_Ultility_CommonViewParamater::LAST_VALUE_HARDWARE] = $valueType;
								$chartIds = '';
								$chartList =    $hardwareTable->getChartIds($h['hardwareid'],$h['valuetype']);
								if ($chartList) { 
									foreach ($chartList as $c) {
										if ($chartIds == '') {
											$chartIds = $c['chart'];
										} else {
											$chartIds = $chartIds . ',' .  $c['chart'];
										}
									}
								}
								$h['chart'] = $chartIds;
								$h[Sss_Ultility_CommonViewParamater::CREATED_DATE_MAX] = $createdDayMax;
								$h[Sss_Ultility_CommonViewParamater::SHOW_VALUE] = $arrValueType[3];
								if ($valueType) {
									//Start check hardware status
									$h[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_OFFLINE;
									if(Sss_Ultility_Common::checkHardwareOnline($createdDayMax)) {
										$h[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_ONLINE;
										$statusNetwork = true;
									} else {
										$statusNetwork = false;
									}
									if(Sss_Ultility_Common::checkHardwareBadConnection($h['hardwareid'],$h['vendor'],$typeCode)) {
										$h[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_BAD_CONNECTION;
									}
									if(Sss_Ultility_Common::checkHardwareOfline($createdDayMax)) {
										$h[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_OFFLINE;
									}
									$netWork[$count][Sss_Ultility_CommonViewParamater::STATUS_NETWORK] = $statusNetwork;
									$netWork[$count]['vendor'] = $h['vendor'];
									$netWork[$count]['vendorname'] = $h['vendorname'];
									$netWork[$count]['stocklocation'] = $h['stocklocation'];
									$arrNetwork[$count] = $netWork;
									//End check hardware status
									$arrHardware[$count] = $h;
									$iCount = $iCount + 1;
								}
								$count = $count + 1;
							}
						}
						if (!empty($arrHardware)) {
							$listSensor[] = $arrHardware;
						}
					}
					$arrStatusNetwork = Sss_Ultility_Common::getStatusNetwork($arrNetwork);
				}
				catch (Exception $e) {
					Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
				}
				if (isset($params[Sss_Ultility_CommonViewParamater::LIMIT_HARDWARE])) {
					$limitHardware = $params[Sss_Ultility_CommonViewParamater::LIMIT_HARDWARE];
				} else {
					$limitHardware = 0;
				}
				$paginationHardware = $paginationRoom;
				$paginationHardware->limitHardware = $limitHardware;
				$refloorplan = $filterParam['stocklocation'];
				$this->view->assign(Sss_Ultility_CommonViewParamater::LIST_SENSOR, $listSensor);
				$this->view->assign(Sss_Ultility_CommonViewParamater::PAGINATION_HARDWARE, $paginationHardware);
				$this->view->assign(Sss_Ultility_CommonViewParamater::RE_FLOORPLAN, $refloorplan);
				$this->view->assign(Sss_Ultility_CommonViewParamater::FLOORPLANS, $floorplans);
				$this->view->assign(Sss_Ultility_CommonViewParamater::ROOMS, $rooms);
				$this->view->assign(Sss_Ultility_CommonViewParamater::FILTER_PARAM, $filterParam);
				$this->view->assign(Sss_Ultility_CommonViewParamater::COUNT_PAGGING, $iCount);
				$this->view->assign(Sss_Ultility_CommonViewParamater::STATUS_NETWORK, $arrStatusNetwork);  

				//Get breadscrumb
				$breadscrumbs = array(
				new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
				new Sss_CommonEntity_BreadScrumb(Resources::_('FLOORPLAN'), '#')
				);
				$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
			}
		}
		public function ajaxLocalizationAction()
		{
			$salocdataTable = new Application_Model_Mapper_SalocData();
			$params = $this->_request->getParams();
			$localizationValue  = $params[Sss_Ultility_CommonViewParamater::LOCALIZATION] ? 1 : 0;
			$localization = new Zend_Session_Namespace(Sss_Ultility_SessionName::LOCALIZATION_SESSION_FLOORPLAN . $this->getCurrentHandle());
			$localization->localization = $localizationValue;
			$filterParam['floorplan'] = $this->getValueRequest('floorplan', $this->getRequest()->getParam('floorplan', Sss_Ultility_CommonViewParamater::UNDERFINE), Sss_Ultility_SessionName::FLOORPLAN_SESSION);
			$floorplanId = $filterParam['floorplan'];
			$arrConvertCoordinate = Sss_Ultility_Common::convertCoordinatesToPixels();
			if(!empty($arrConvertCoordinate)){
				$arrBlueGreen = Sss_Ultility_LocalizationConfigurationFloorplan::configfloorplan();
			}
			$index = 0;
			foreach ($arrConvertCoordinate as $k => $v) {
				if($floorplanId  == $k){
					$valueBlueGreenConfig = $arrBlueGreen[$index];
				}
				$index++;
			}
			//Load data with ajax
			$checkFirstAjax = $params['checkFisrtAjax'];
			if ($localizationValue) {
				$bluePoint = $valueBlueGreenConfig[Sss_Ultility_CommonViewParamater::NODE_FLOORPLAN_COORDINATES];
				$blue = explode(",",$bluePoint);
				$greenPoint = $valueBlueGreenConfig[Sss_Ultility_CommonViewParamater::FIXED_NODE_COORDINATES];
				$green = explode(",",$greenPoint);
				$calculatorUnit = $arrConvertCoordinate[$filterParam['floorplan']];
				$arrCalculatorUnit = explode(",", $calculatorUnit);
				$nodeRelativeCoordinate = explode(",",$valueBlueGreenConfig[Sss_Ultility_CommonViewParamater::NODE_FLOORPLAN_RELATIVE_COORDINATES]);
				if(!empty($valueBlueGreenConfig) && !empty($arrConvertCoordinate)){
					//Coordinates blue point
					$idblue=$valueBlueGreenConfig[Sss_Ultility_CommonViewParamater::NODE_ADDRESS];

					$coordinateGreenPoint=$valueBlueGreenConfig[Sss_Ultility_CommonViewParamater::FIXED_NODE_RELATIVE_COORDINATES];
					$idgreen=$valueBlueGreenConfig[Sss_Ultility_CommonViewParamater::FIXED_NODE_ADDRESS];
					$stringHtml ="<img src=\"/upload/t_icon.png\" id=\"valueBlue\" class=\"checkTooltip\" style=\"position: absolute;  border: 0px; left: $blue[0]px ;top: $blue[1]px;\" />" ;
					$stringHtml.="<div id=\"divValueBlue\" style=\"display:none;\">$idblue - 0,0</div>";
					// Used session to save information Hardware
					$hardwareSession = new Zend_Session_Namespace('hardware');
					$floorplanIdSession = new Zend_Session_Namespace('floorplanID');
					$serialNumberSession = new Zend_Session_Namespace('serialNumber');
					$arrHardwareSerialNumber = array();
					$arrHardwareSession = array();
					if($checkFirstAjax == 0) {
						$getDataSaloc = $salocdataTable->getListSalocDataHardware($floorplanId,$checkFirstAjax);
						foreach ($getDataSaloc as $salochardware) {
							$arrHardwareSession[$salochardware['hardwareid']] = array(
									$salochardware['hardwaretype'],
									$salochardware['allocation'],
									$salochardware['serial_number']
							);
							$floorplanIdSession->floorplanID = $salochardware['floorplan'];
							$arrHardwareSerialNumber[] = $salochardware['serial_number'];
							//Start load saloc data with ajax and when checked checkbox localization
							if($salochardware['floorplan'] == $filterParam['floorplan']) {
								$timeValue = '';
								if(!empty($salochardware['timestamp'])) {
									$timesTamp = explode(".", $salochardware['timestamp']);
									$convert = strtotime($timesTamp[0]);
									$convertTimesTamp = date(DATETIMELONGFORMAT, $convert);
									$timeValue = "- ".$convertTimesTamp.".".$timesTamp[1];
								}
								$getPixelX = (abs($salochardware['x']-$nodeRelativeCoordinate[0]))/$arrCalculatorUnit[0];
								$getPixelY = (abs($salochardware['y']-$nodeRelativeCoordinate[1]))/$arrCalculatorUnit[1];
								if($salochardware['hardwaretype'] == Sss_Ultility_Setting::HARDWARE_TYPE_MOBILE_NODE){
									//Saloc width systemtype id is 12
									$stringHtml .= "<img src=\"/upload/red_icon.png\" class=\"checkTooltip\" id=\"valueHardware".$salochardware['hardwareid']."\" style=\"position: absolute;  border: 0px; left: ".($blue[0] + $getPixelX)."px; top:".round(abs($blue[1] - $getPixelY ), 10)."px\" />";
									$stringHtml .= "<div id=\"divValueHardware".$salochardware['hardwareid']."\" style=\"display:none;\">".$salochardware['serial_number'] ." - ". $salochardware['allocation'] ." - ". $salochardware['x'].",".$salochardware['y']." ".$timeValue."</div>";
								}
								//Saloc width systemtype id is 13
								elseif($salochardware['hardwaretype'] == Sss_Ultility_Setting::HARDWARE_VALUE_TYPE_NOMADIC_NODE){
									$stringHtml .= "<img src=\"/upload/screen_icon.png\" class=\"checkTooltip\" id=\"valueHardware".$salochardware['hardwareid']."\" style=\"position: absolute;  border: 0px; left: ".($blue[0] + $getPixelX)."px; top:".round(abs($blue[1] - $getPixelY ), 10)."px\"/>";
									$stringHtml .= "<div id=\"divValueHardware".$salochardware['hardwareid']."\" style=\"display:none;\">".$salochardware['serial_number'] ." - ". $salochardware['allocation'] ." - ". $salochardware['x'].",".$salochardware['y']." ".$timeValue."</div>";
								}
								//saloc width systemtype id is 93
								elseif($salochardware['hardwaretype'] == Sss_Ultility_Setting::HARDWARE_VALUE_TYPE_REFERENCE_NOTE){
									$stringHtml .= "<img src=\"/upload/t_icon.png\" class=\"checkTooltip\" id=\"valueHardware".$salochardware['hardwareid']."\" style=\"position: absolute;  border: 0px; left: ".($blue[0] + $getPixelX)."px; top:".round(abs($blue[1] - $getPixelY ), 10)."px\"/>";
									$stringHtml .= "<div id=\"divValueHardware".$salochardware['hardwareid']."\" style=\"display:none;\">".$salochardware['serial_number'] ." - ". $salochardware['allocation'] ." - ". $salochardware['x'].",".$salochardware['y']." ".$timeValue."</div>";
								}
							}
						}
						$serialNumberSession->serialNumber = $arrHardwareSerialNumber;
						$hardwareSession->hardware = $arrHardwareSession;
					} else {
						$getDataSaloc = $salocdataTable->getListSalocDataHardware($floorplanId,$checkFirstAjax,$serialNumberSession->serialNumber);
						foreach ($getDataSaloc as $salochardware) {
							if($floorplanIdSession->floorplanID == $filterParam['floorplan']) {
								$timeValue = '';
								if(!empty($salochardware['timestamp'])){
									$timesTamp = explode(".", $salochardware['timestamp']);
									$convert = strtotime($timesTamp[0]);
									$convertTimesTamp = date(DATETIMELONGFORMAT, $convert);
									$timeValue = "- ".$convertTimesTamp.".".$timesTamp[1];
								}
								$getPixelX = (abs($salochardware['x']-$nodeRelativeCoordinate[0]))/$arrCalculatorUnit[0];
								$getPixelY = (abs($salochardware['y']-$nodeRelativeCoordinate[1]))/$arrCalculatorUnit[1];
								foreach($hardwareSession->hardware as $key => $value) {
									if ($value[2] == $salochardware['salocid']) {
										if($value[0] == Sss_Ultility_Setting::HARDWARE_TYPE_MOBILE_NODE) {
											//Saloc width systemtype id is 12
											$stringHtml .= "<img src=\"/upload/red_icon.png\" class=\"checkTooltip\" id=\"valueHardware".$key."\" style=\"position: absolute;  border: 0px; left: ".($blue[0] + $getPixelX)."px; top:".round(abs($blue[1] - $getPixelY ), 10)."px\" />";
											$stringHtml .= "<div id=\"divValueHardware".$key."\" style=\"display:none;\">".$value[2] ." - ". $value[1] ." - ". $salochardware['x'].",".$salochardware['y']." ".$timeValue."</div>";
										}
										//Saloc width systemtype id is 13
										elseif($value[0] == Sss_Ultility_Setting::HARDWARE_VALUE_TYPE_NOMADIC_NODE){
											$stringHtml .= "<img src=\"/upload/screen_icon.png\" class=\"checkTooltip\" id=\"valueHardware".$key."\" style=\"position: absolute;  border: 0px; left: ".($blue[0] + $getPixelX)."px; top:".round(abs($blue[1] - $getPixelY ), 10)."px\"/>";
											$stringHtml .= "<div id=\"divValueHardware".$key."\" style=\"display:none;\">".$value[2]." - ". $value[1] ." - ". $salochardware['x'].",".$salochardware['y']." ".$timeValue."</div>";
										}
										//saloc width systemtype id is 93
										elseif($value[0] == Sss_Ultility_Setting::HARDWARE_VALUE_TYPE_REFERENCE_NOTE){
											$stringHtml .= "<img src=\"/upload/t_icon.png\" class=\"checkTooltip\" id=\"valueHardware".$key."\" style=\"position: absolute;  border: 0px; left: ".($blue[0] + $getPixelX)."px; top:".round(abs($blue[1] - $getPixelY ), 10)."px\"/>";
											$stringHtml .= "<div id=\"divValueHardware".$key."\" style=\"display:none;\">".$value[2]." - ". $value[1] ." - ". $salochardware['x'].",".$salochardware['y']." ".$timeValue."</div>";
										}
									}
								}
							}
						}
					}
					//Coordinates green point
					$stringHtml .="<img src=\"/upload/t_icon.png\" class=\"checkTooltip\" id=\"valueGreen\" style=\"position: absolute;  border: 0px; left: $green[0]px; top: $green[1]px\"/>";
					$stringHtml .="<div id=\"divValueGreen\" style=\"display:none;\">".$idgreen." - ".$coordinateGreenPoint."</div>";
					}
					// Display html to view
					echo $stringHtml;
			}
			die;
			//End
		}

		public function graphsAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/monitoring-localization/geomapping");
			}
			$post           = $this->getRequest()->getPost();
			$get            = $this->getRequest();
			$handle         = $get->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$containerTable = new Shepherd_Model_Mapper_Container();
			$shipmentTable  = new Shepherd_Model_Mapper_Shipment();
			$itemTable      = new Shepherd_Model_Mapper_Item();
			$graphTable     = new Shepherd_Model_Mapper_Graph();
			$graphContructor = new Shepherd_Model_Graph();
			$chartTable = new Shepherd_Model_Mapper_Chart();
			$chartContructor = new Shepherd_Model_Chart();


			$presetGraphTable = new Shepherd_Model_Mapper_PresetGraph();
			$chartSessionTable     = new Shepherd_Model_Mapper_ChartSession();

			$instanceTable  = new Application_Model_Mapper_Instance();
			$shipmentDynamicMonitorings = $shipmentTable->getDynamicMonitoringList(true);
			$itemDynamicMonitorings     = $itemTable->getDynamicMonitoringList();
			$rooms                      = $containerTable->getAllRoomByIsUsed();
			$queryString     = $get->getParam('chart');
			$hardwareId = $get->getParam('hardwareid');
			$floorPlan       = $this->getRequest()->getParam("f", -1);
			$valueType = $get->getParam('valuetype');
			$chartList = $get->getParam('chart');
			if (!is_null($hardwareId) && !is_null($valueType) && !empty($valueType) && !empty($hardwareId)) {
				$arrSavedCharts = $this->loadSaveCharts();
				$start = 0;
				$end = 0;
				if($floorPlan != -1){
					$arrSavedCharts = array();
					$timeRangeTypeValue = 3; 
					$instance = $instanceTable->getInstanceByHandle($handle); 
					$end = strtotime(date(DATETIME_MYSQL_FORMAT));
					$start = $end-(24*60*60);
					$checkRimeRangNull = $graphTable->checkTimeRangNull($hardwareId,$valueType, $start);
					if($checkRimeRangNull){
						$arrDate = $graphTable->getTimeRangDefault($hardwareId, $valueType, $instance->instanceid);
						$end = $arrDate[0];
						$start = $arrDate[1];
					}
				}else{ 
					$timeRangeTypeValue = 3;
					$end = strtotime(date(DATETIME_MYSQL_FORMAT));
					$start = $end - (24*60*60);
				}
				$dateShipment       = $this->getRequest()->getParam("date", -1);
				$dateEndShipment       = $this->getRequest()->getParam("enddate", -1);

				if($dateShipment != -1)  {
					$timeRangeTypeValue = 3;
					$start = strtotime(date(DATETIME_MYSQL_FORMAT, $dateShipment),$dateShipment);
				}
				if($dateEndShipment != -1){
					$timeRangeTypeValue = 3;
					$end = strtotime(date(DATETIME_MYSQL_FORMAT, $dateEndShipment),$dateEndShipment); 
				}
				$chartContructor->setChartName(Resources::_('DEFAULT_CHART_NAME'));
				$chartContructor->setFromDatetime($start);
				$chartContructor->setToDatetime($end);
				$chartContructor->setFromValue(0);
				$chartContructor->setToValue(0);
				$chartContructor->setCreatedBy($userInformation->accountid);
				$chartContructor->setUpdatedBy($userInformation->accountid);
				$chartContructor->setCreatedDate(strtotime('now'));
				$chartContructor->setUpdatedDate(strtotime('now'));
				$chartContructor->setHardware($hardwareId);
				$chartContructor->setTimeRangeType($timeRangeTypeValue);
				$chartContructor->setAverageValue(0);
				$chartContructor->setFilterValue(0);
				$chartContructor->setSmoothingValue(0);
				$insertChartId   = $chartTable->save($chartContructor,$instance->instanceid);
				if (isset($insertChartId) && (int) $insertChartId > 0) {
					$updateChart = $chartTable->findById($insertChartId,$instance->instanceid);
					$updateChart->setChartName(Resources::_('DEFAULT_CHART_NAME') . ' ' . sprintf('%03d', $insertChartId));
					$chartTable->save($updateChart,$instance->instanceid);
					$arrChartList[] = $insertChartId;
					$queryString = count($arrChartList) > 0 ? '?chart=' . implode(',', $arrChartList) : '';
					//insert Graph
					$graphContructor->setGraphName(Resources::_('DEFAULT_GRAPH_NAME'));
					$graphContructor->setChart($insertChartId);
					$graphContructor->setColor(Resources::_('DEFAULT_GRAPH_COLOR'));
					$graphContructor->setHardware($hardwareId);
					$graphContructor->setValueType($valueType);
					$insertGraphId = $graphTable->save($graphContructor,$instance->instanceid);
					if (isset($insertGraphId) && (int) $insertGraphId > 0) {
						$updateGraph = $graphTable->findById($insertGraphId,$instance->instanceid);
						$updateGraph->setGraphName(Resources::_('DEFAULT_GRAPH_NAME') . ' ' . sprintf('%03d', $insertGraphId));
						$graphTable->save($updateGraph,$instance->instanceid);
						$this->redirect(Resources::_('ADD_NEW_GRAPH_SUCCESSFUL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
						)) . "?" . 'chart' . "=" . (count($arrSavedCharts) > 0 ? implode(',', $arrSavedCharts) . ',' . $insertChartId : $insertChartId));
					} else {
						$this->redirect(Resources::_('SAVE_GRAPH_FAILED'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
						)) . (count($arrSavedCharts) > 0 ? "?".'chart' . "=" . implode(',', $arrSavedCharts) : ''));
					}
				}
				$this->redirect('', $this->view->url(array(Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName, Sss_Ultility_CommonViewParamater::ACTION => 'graphs')).(count($arrSavedCharts) > 0 ? "?chart=" . implode(',', $arrSavedCharts) : ""));
			} else { 
				if ($queryString == '' && isset($_GET['chart'])) {
					$this->view->assign(Sss_Ultility_CommonViewParamater::MSG, Resources::_('NOT_CONFIGURE_VALUE_TYPE'));
				}
			}

			$arrChartList    = array();
			if ($queryString != '') {
				$arrChartList = explode(',', $queryString);
			}
			if ( isset($post['deleteAction']) && isset($post['deleteChartId']) && $post['deleteAction'] == 'DELETEACTION' && (int)$post['deleteChartId'] > 0 ) {
				$arrChartId = array();
				if ((int)$post['type'] == 1) {  
					$dataChart = $chartTable->getChartListByPreset($post['deleteChartId']); 
					foreach ($dataChart as $v) {  
						$chartSessionTable->deleteRow(null,array('chart = ?'=>$v['chartid']), $instance->instanceid);
						if (count($arrChartList) > 0) {
							$key = array_search($v['chartid'], $arrChartList);
							unset($arrChartList[$key]);
						}
					}
				} else {
					$chartSessionTable->deleteRow(null,array('chart = ?'=>$post['deleteChartId']), $instance->instanceid);
					$graphTable->deleteRecord(array('chart'=>$post['deleteChartId']), true);
					$chartTable->deleteRecord(array('chartid'=>$post['deleteChartId']), true);
					if (count($arrChartList) > 0) {
						$key = array_search($post['deleteChartId'], $arrChartList);
						unset($arrChartList[$key]);
					}
				}
				$queryString     = count($arrChartList) > 0 ?  'chart' . '=' . implode(',', $arrChartList) : '';
				$this->redirect(Resources::_('DELETE_GRAPH_SUCCESSFULL'), $this->view->url(array(
				Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
				Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
				)) . '?' . $queryString);
			}

			$queryString     = count($arrChartList) > 0 ?  implode(',', $arrChartList) : '';
			if (isset($post['btnSaveGraph'])) {
				if($post['typeGraph'] == '1') {
					$presetGraphTable->updateValueRangeofGraph($post['hdGraphId'], $post['txtGraphFromValue'], $post['txtGraphToValue']);
				} else {
					$graphTable->updateValueRangeofGraph($post['hdGraphId'], $post['txtGraphFromValue'], $post['txtGraphToValue']);
				}
			}
			//load ajax of chart on popup graphs
			$limit = $get->getParam('limit');
			$checkChart = $get->getParam('checkChart');
			$textSearch = $get->getParam('textSearch');
			$getArrayChartId = $get->getParam('arrChartId');
			$arrChartId = explode(",",$getArrayChartId);
			$arrayChartId = $chartList == '' ? array() : explode(',', $chartList);
			if($checkChart == 'chart') {
				$page = $get->getParam(Sss_Ultility_CommonViewParamater::PAGE);
				$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = $page ? $page : 1;
				if($textSearch == "Name" || empty($textSearch)) {
					$arrSaved = $chartSessionTable->getSavedChartsByAccount($userInformation->accountid,'',$limit,0,$filterParam);
				} else {
					$arrSaved = $chartSessionTable->getSavedChartsByAccount($userInformation->accountid,$textSearch,$limit,0,$filterParam);
				}
				$i=1;
				$arrSavedCharts = $arrSaved->list;
				$pagination = $arrSaved->pagination;
				$stringHtmlChart = '';
				$stringHtmlChart.= "<table class='lvt small' cellspacing='1' cellpadding='3' border='0' width='100%'>";
				foreach ($arrSavedCharts as $val) {
					$arrTmpCharts = $arrChartId; 
					$arrTmpCharts[] = $val['chartid'];
					$stringHtmlChart.= "<tr bgcolor=\"white\" onmouseout=\"this.className='lvtColData'\" onmouseover=\"this.className='lvtColDataHover'\" class=\"lvtColData\">";
					$stringHtmlChart.= "<td align='center' style='width:20px;'>".$i."</td>";
					$stringHtmlChart.= "<td style='width:320px;'><a href=" . $this->view->url(array(Sss_Ultility_CommonViewParamater::CONTROLLER => 'monitoring-localization', Sss_Ultility_CommonViewParamater::ACTION => 'graphs')) . "?chart=" . implode(',', $arrTmpCharts) . ">" . $val['chartname'] . "</a></td>";
					$stringHtmlChart.= "<td>" . (is_null($val['notes']) ? '' : $val['notes']) . "</td>";
					$stringHtmlChart.= "<td align='center' style='width:50px;'>";
					if((int) $val['created'] == 1) { 
						$stringHtmlChart.= "<a href='javascript:deleteSavedChart(" . $val['chartid'] . " ,0);void(0)'>" . Resources::_('BTN_DELETE') . "</a>";
					}
					$stringHtmlChart.= "</td>";
					$stringHtmlChart.= "</tr>";
					$i++;
				}
				$stringHtmlChart.= "</table>";
				$stringHtmlChart.= Sss_Grid::ajaxPresetPagiHtml($pagination, $this->view->baseUrl(),$getArrayChartId,$checkChart,null);
				echo $stringHtmlChart;
				die;
			}
			//End load ajax of chart

			//load ajax of preset on popup graphs

			if($checkChart == 'preset') {
				$page = $get->getParam(Sss_Ultility_CommonViewParamater::PAGE);
				$filterParam[Sss_Ultility_CommonViewParamater::PAGE] = $page ? $page : 1;
				$arrPresetId = array();
				$arrPresetChart = array();
				//get data of preset and presetchart
				if($textSearch == "Name" || empty($textSearch)) {
					$arrPreset = $chartSessionTable->getPresetByChartSession('',$limit,0,$filterParam);
				} else {
					$arrPreset = $chartSessionTable->getPresetByChartSession($textSearch,$limit,0,$filterParam);
				}
				$arrPresetList = $arrPreset->list;
				$pagination = $arrPreset->pagination;
				foreach ($arrPresetList as $d) {
					$arrPresetId[]= array('presetid' => $d['presetid'], 'presetname' => $d['presetname']);
				}
				foreach ($arrPresetId as $presetId) {
					$arrPresetChart[$presetId['presetid']] = $chartTable->getChartListByPreset($presetId['presetid']);
				}
				$i = 1; 
				$stringHtml = "<table class='lvt small' cellspacing='1' cellpadding='3' border='0' width='100%'>";
				foreach ($arrPresetId as $preset) {
					$arrTmpCharts = $arrChartId;
					foreach ($arrPresetChart[$preset['presetid']] as $presetChartId) {
						foreach ($presetChartId as $item) { 
							$arrTmpCharts[] = $item;
						}
					}
					$stringHtml.= "<tr bgcolor='white' onmouseout=\"this.className='lvtColData'\" onmouseover=\"this.className='lvtColDataHover'\" class='lvtColData'>";
					$stringHtml.= "<td align='center' style='width:20px;'>$i</td>";
					$stringHtml.= "<td style='width:320px;'><a href='" . $this->view->url(array(Sss_Ultility_CommonViewParamater::CONTROLLER => 'monitoring-localization', Sss_Ultility_CommonViewParamater::ACTION => 'graphs')) . "?chart=" . implode(",", $arrTmpCharts) . "'>".$preset['presetname']."</a></td>";
					$stringHtml.= "<td></td>";
					$stringHtml.= "<td align='center' style='width:50px;'>";
					$stringHtml.= "<a href='javascript:deleteSavedChart(".$preset['presetid'].",1);void(0)'>".Resources::_('BTN_DELETE')."</a>";
					$stringHtml.= "</td>";
					$stringHtml.= "</tr>";
					$i++;
				}
				$stringHtml.= "</table>";
				$stringHtml.= Sss_Grid::ajaxPresetPagiHtml($pagination,$this->view->baseUrl(),$getArrayChartId,$checkChart,null);
				echo $stringHtml;
				die;
			}
			//End load ajax of preset

			//get button add new configuration
			$actionbuttons = array(
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ADD, "javascript:showAddAction();void(0);", Resources::_('ADD_GRAPH')),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::PRINTC, "javascript:printAllChart();", Resources::_('PRINT_ALL_CHARTS'),''),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::MERGE, "javascript:showExpandMergeChart('" . Resources::_('EXPAND_MERGE_GRAPHS') . "')", Resources::_('EXPAND_MERGE_GRAPHS')),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ANALYSE, '/' . $handle . '/analysis', Resources::_('ANALYSE')),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::EXPORT, "javascript:graphExportCsv();", Resources::_('EXPORT'), ''),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::LISTITEM, "javascript:showSavedCharts();void(1);", Resources::_('LOAD_SAVED_CHARTS')),
			new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ADDPRESET,"javascript:showAddPreset();void(0);", Resources::_('ADD_PRESET'))
			);
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_ANALYSIS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ){
				$actionbuttons = array(
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ADD, "javascript:showAddAction();void(0);", Resources::_('ADD_GRAPH')),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::PRINTF, "javascript:printAllChart();", Resources::_('PRINT_ALL_CHARTS'),''),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::MERGE, "javascript:showExpandMergeChart('" . Resources::_('EXPAND_MERGE_GRAPHS') . "')", Resources::_('EXPAND_MERGE_GRAPHS')),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::EXPORT, "javascript:graphExportCsv();", Resources::_('EXPORT'), ''),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::LISTITEM, "javascript:showSavedCharts();void(1);", Resources::_('LOAD_SAVED_CHARTS')),
				new Sss_CommonEntity_ActionButton(Sss_Ultility_ActionButtonType::ADDPRESET,"javascript:showAddPreset();void(0);", Resources::_('ADD_PRESET'))
				);
			}
			$this->view->assign(Sss_Ultility_CommonViewParamater::ACTION_BUTTONS, $actionbuttons);
			//get breadscrumb
			$breadscrumbs  = array(
			new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
			new Sss_CommonEntity_BreadScrumb('Graphs', '#')
			);
			$sessionQueryString = new Zend_Session_Namespace('queryString');
			$sessionQueryString->queryString = $queryString;
			$chartSessionTable->getSavedChartsByAccount($userInformation->accountid);
			$this->view->assign('arrSavedCharts', $arrSavedCharts);
			$this->view->assign('arrChartId', $arrayChartId);
			$this->view->assign('handle', $handle);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ROOMS, $rooms);
			$this->view->assign(Sss_Ultility_CommonViewParamater::SHIPMENTS, $shipmentDynamicMonitorings);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ITEMS, $itemDynamicMonitorings);
			$this->view->assign('arrPresetId',$arrPresetId);
			$this->view->assign('arrPresetChart',$arrPresetChart);
			$this->view->assign('chartList',$chartList);
		}

		public function addNewGraphAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 )
			{
				$this->_redirect("/$handle/user/login");
			}
			$params    = $this->getRequest()->getPost();
			$getParams = $this->_request->getParams();
			$arrChartList    = array();
			$queryString     = $getParams['chart'];
			if ($queryString != '') {
				$arrChartList = explode(',', $queryString);
			}
			$queryString     = count($arrChartList) > 0 ? 'chart' . '=' . implode(',', $arrChartList) : '';
			$hardwareTable   = new Application_Model_Mapper_Hardware();
			$containerTable  = new Shepherd_Model_Mapper_Container();
			$systemTypeTable = new Shepherd_Model_Mapper_SystemType();
			$chartTable      = new Shepherd_Model_Mapper_Chart();
			$shipmentTable   = new Shepherd_Model_Mapper_Shipment();
			$itemTable       = new Shepherd_Model_Mapper_Item();
			$graphTable      = new Shepherd_Model_Mapper_Graph();
			$presetGraphTable = new Shepherd_Model_Mapper_PresetGraph();
			$presetChartTable = new Shepherd_Model_Mapper_PresetChart();
			$presetTable      = new Shepherd_Model_Mapper_Preset();
			$shipmentDynamicMonitorings = $shipmentTable->getDynamicMonitoringList();
			$itemDynamicMonitorings     = $itemTable->getDynamicMonitoringList();
			$systemTypes                = $systemTypeTable->getSystemBySystemName(Sss_Ultility_SystemName::TIME_RANGE_TYPE);
			$rooms                      = $containerTable->getAllRoomByIsUsed();
			$chartId = isset($getParams['chartid']) ? (int) $getParams['chartid'] : 0;
			$graphId = isset($getParams['graphid']) ? (int) $getParams['graphid'] : 0;
			$presetChartid = isset($getParams['presetchartid']) ? (int) $getParams['presetchartid'] : 0;
			$isUpdate = (int) $chartId > 0 && (int) $graphId > 0;
			if ($isUpdate) {
				if( $presetChartid != 0 ) {
					$updatedChart     = $presetChartTable->findById($chartId,$instance->instanceid);
					$updatedGraph     = $presetGraphTable->findById($graphId,$instance->instanceid);
					$updatedPreset    = $presetTable->findById($updatedChart->preset,$instance->instanceid);
				} else {
					$updatedChart     = $chartTable->findById($chartId,$instance->instanceid);
					$updatedGraph     = $graphTable->findById($graphId,$instance->instanceid);
				}
				$OvisSystemTypeTable = new Application_Model_Mapper_SystemType();
				$updatedValueType    = isset($updatedGraph) ? $OvisSystemTypeTable->findById($updatedGraph->valuetype) : null;
				$updatedHardware     = isset($updatedGraph) ? $hardwareTable->findById((int) $updatedGraph->hardware) : null;
				$this->view->assign('presetChartId',$presetChartid);
				$this->view->assign('updatedChart', $updatedChart);
				$this->view->assign('updatedGraph', $updatedGraph);
				$this->view->assign('updatedPreset',$updatedPreset);
				$this->view->assign('updatedHardwareName', isset($updatedHardware) ? $updatedHardware->hardwarename : '');
				$this->view->assign('updatedHardwareSerialNumber', isset($updatedHardware) ? $updatedHardware->serialNumber : '');
				$this->view->assign('updatedValueTye', isset($updatedValueType) ? $updatedValueType->typename : '');
				$this->view->assign('urlBack',$urlBack);
			}

			if (isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) { 
				if ($isUpdate) {
					$arrTable = array('presetTable' => $presetTable,
										'presetChartTable' => $presetChartTable,
										'presetGraphTable' => $presetGraphTable,
										'chartTable'		=> $chartTable,
										'graphTable'		=> $graphTable
					);
					Sss_Ultility_MonitoringLocalizationFuction::updateChartRes($arrTable,$presetChartid,$userInformation,$params,$updatedPreset,$chartId,$graphId);
					$this->redirect(Resources::_('UPDATE_GRAPH_SUCCESSFUL'), $this->view->url(array(
					Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
					Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
					)) . '?' . $queryString);
				}
			}
			//get breadscrumb
			$breadscrumbs = array(
			new Sss_CommonEntity_BreadScrumb(Resources::_('MONITORING_LOCALIZATION'), ''),
			new Sss_CommonEntity_BreadScrumb(Resources::_('GRAPHS'), '#'),
			new Sss_CommonEntity_BreadScrumb($isUpdate ? Resources::_('UPDATE_GRAPH') : Resources::_('ADD_NEW_GRAPH'), '#')
			);
			$this->view->assign(Sss_Ultility_CommonViewParamater::QUERY_STRING, $queryString);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ROOMS, $rooms);
			$this->view->assign(Sss_Ultility_CommonViewParamater::TIME_RANGE_TYPE, $systemTypes);
			$this->view->assign(Sss_Ultility_CommonViewParamater::SHIPMENTS, $shipmentDynamicMonitorings);
			$this->view->assign(Sss_Ultility_CommonViewParamater::ITEMS, $itemDynamicMonitorings);
		}

		public function addOnExistedChartAction()
		{

			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$defaultOvisNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_SHEPHERD_SYSTEM . $handle);
			$instanceId = $defaultOvisNamespace->dbShepherd;
			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$params      = $this->getRequest()->getPost();
			$getParams   = $this->_request->getParams();

			$graphTable     = new Shepherd_Model_Mapper_Graph();
			$chartTable     = new Shepherd_Model_Mapper_Chart();

			$isClose = 0;
			$selectedHardware = $getParams['hardwareid'];
			$selectedValueType = $getParams[Sss_Ultility_CommonViewParamater::VALUE_TYPE];
			$selectedColors = $getParams[Sss_Ultility_CommonViewParamater::COLOR_LIST];
			$selectedGraphNames     = $getParams[Sss_Ultility_CommonViewParamater::GRAPH_NAME_LIST];

			if ($selectedHardware == '' || $selectedValueType == '' || $selectedColors == '' || $selectedGraphNames == '') {
				$isClose = 1;
			}
			$arrayCharts = array();
			$arrayOtherCharts = array();
			$chartIds = $getParams['chartid'];
			if ($chartIds != '') {
				$arrayCharts = $chartTable->getChartListByChartIdList($chartIds);
				$arrayOtherCharts = $chartTable->getOtherChartListByChartIdList($chartIds);
			}
			if (isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
				$selectedChartValue = $params['cboDestinationChart'];
				$listColor = $graphTable->getColorListGraphByChart($selectedChartValue);
				$arrHardware = explode(',', $selectedHardware);
				$arrValueTypes = explode(',', $selectedValueType);
				$arrColors = explode(',', $selectedColors);
				$arrGraphNames = explode(',', $selectedGraphNames);
				foreach ($listColor as $listColor) {
					$arrCheckColor[] = $listColor['color'];
				}
				foreach ($arrHardware as $i=>$hr) {
					if(in_array("#".$arrColors[$i], $arrCheckColor)) {
						$color   = Sss_Ultility_Common::genRandomColor();
					} else {
						$color = $arrColors[$i];
					}
					$graphContructor = new Shepherd_Model_Graph();
					$graphContructor->setChart($selectedChartValue);
					$graphContructor->setColor('#' . $color);
					$graphContructor->setHardware($hr);
					$graphContructor->setGraphName(addslashes($arrGraphNames[$i]));
					$graphContructor->setValueType($arrValueTypes[$i]);
					$insertGraphId = $graphTable->save($graphContructor,$instanceId);
					if (isset($insertGraphId) && (int) $insertGraphId > 0) {
						$graphTable->consistanceValueRange($selectedChartValue, $insertGraphId, $arrValueTypes[$i],$instanceId);
					}
				}
				$isClose = 1;
			}
			$this->view->assign('isClosed', $isClose);
			$this->view->assign('savedCharts', $arrayCharts);
			$this->view->assign('otherCharts', $arrayOtherCharts);
			$this->view->assign('chartIds',$chartIds);
		}

		public function addOnExistedPresetAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$defaultOvisNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_SHEPHERD_SYSTEM . $handle);
			$instanceId = $defaultOvisNamespace->dbShepherd;
			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$params      = $this->getRequest()->getPost();
			$getParams   = $this->_request->getParams();

			$presetTable      = new Shepherd_Model_Mapper_Preset();

			$presetChartTable = new Shepherd_Model_Mapper_PresetChart();
			$presetChartContructor = new Shepherd_Model_PresetChart();
			$presetGraphTable = new Shepherd_Model_Mapper_PresetGraph();
			$chartTable      = new Shepherd_Model_Mapper_Chart();
			$chartContructor = new Shepherd_Model_Chart();
			$graphTable     = new Shepherd_Model_Mapper_Graph();

			$queryString     = isset($getParams['chartid']) ? $getParams['chartid'] : '';
			$arrChartList    = array();
			if ($queryString != '') {
				$arrChartList = explode(',', $queryString);
			}
			$queryString     = count($arrChartList) > 0 ? "?".'chart' . '=' . implode(',', $arrChartList).'&' : '';
			$isClose = 0;
			$selectedHardware = $getParams['hardwareid'];
			$selectedValueType = $getParams[Sss_Ultility_CommonViewParamater::VALUE_TYPE];
			$selectedColors = $getParams[Sss_Ultility_CommonViewParamater::COLOR_LIST];
			$selectedGraphNames     = $getParams[Sss_Ultility_CommonViewParamater::GRAPH_NAME_LIST];
			$type     = $getParams[Sss_Ultility_CommonViewParamater::TYPE];
			$row       = $presetTable->getByPreset();
			if ($selectedHardware == '' || $selectedValueType == '' || $selectedColors == '' || $selectedGraphNames == '') {
				$isClose = 1;
			}
			if (isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])) { 
				$valueChart = $params['cboChartPreset'];
				$arrHardware = explode(',', $selectedHardware);
				$arrColors = explode(',', $selectedColors);
				$arrValueTypes = explode(',', $selectedValueType);
				$arrGraphNames = explode(',', $selectedGraphNames);
				$presetId = $params['cboDestinationPreset'];
				$charts = $presetChartTable->getChartListByPresetId($presetId);
				//Add new preset chart when value 0
				if(empty($valueChart)) {
					$end = strtotime(date(DATETIME_MYSQL_FORMAT));
					$start = $end - 24*60*60;
					$timeRangeTypeValue = 3;
					//set value of chart
					$chartContructor->setChartName(Resources::_('DEFAULT_CHART_NAME'));
					$chartContructor->setFromDatetime($start);
					$chartContructor->setToDatetime($end);
					$chartContructor->setFromValue(0);
					$chartContructor->setToValue(0);
					$chartContructor->setCreatedDate(time());
					$chartContructor->setUpdatedDate(time());
					$chartContructor->setCreatedBy($userInformation->accountid);
					$chartContructor->setUpdatedBy($userInformation->accountid);
					$chartContructor->setHardware($arrHardware[0]);
					$chartContructor->setTimeRangeType($timeRangeTypeValue);
					$chartContructor->setAverageValue(0);
					$chartContructor->setFilterValue(0);
					$chartContructor->setSmoothingValue(0);
					if($type == Sss_Ultility_CommonViewParamater::CHARTS) {
						//Insert tables charts when click add new graph with preset
						$insertChartId   = $chartTable->save($chartContructor,$instanceId);
						if (isset($insertChartId) && (int) $insertChartId > 0) {
							$updateChart = $chartTable->findById($insertChartId,$instanceId);
							$updateChart->setChartName(Resources::_('DEFAULT_CHART_NAME') . ' ' . sprintf('%03d', $insertChartId));
							$chartTable->save($updateChart,$instanceId);
						}
						foreach ($arrHardware as $i=>$sensor) {
							$graphContructor = new Shepherd_Model_Graph();
							$graphContructor->setChart($insertChartId);
							$graphContructor->setColor('#' . $arrColors[$i]);
							$graphContructor->setHardware($sensor);
							$graphContructor->setGraphName(addslashes($arrGraphNames[$i]));
							$graphContructor->setValueType($arrValueTypes[$i]);
							$insertGraphId = $graphTable->save($graphContructor,$instanceId);
							if (isset($insertGraphId) && (int) $insertGraphId > 0) {
								$graphTable->consistanceValueRange($insertChartId, $insertGraphId, $arrValueTypes[$i],$instanceId);
							}
						}
						//add preset graph if click add new graph
						foreach ($charts as $c) { 
							$getDataGraph = $presetGraphTable->getGraphListByChartId((int)$c['presetchartid']);
							foreach ( $getDataGraph as $dataGraph ) { 
								$checkGraphExists = $graphTable->getGraphByHardwareAndValueType($dataGraph['hardware'],$dataGraph['valuetype'],$insertChartId);
								if ( empty($checkGraphExists) ) {
									$graphContructor = new Shepherd_Model_Graph();
									$graphContructor->setChart($insertChartId);
									$graphContructor->setColor($dataGraph['color']);
									$graphContructor->setHardware($dataGraph['hardware']);
									$graphContructor->setGraphName($dataGraph['graphname']);
									$graphContructor->setValueType($dataGraph['valuetype']);
									$insertGraphId = $graphTable->save($graphContructor,$instanceId);
									if (isset($insertGraphId) && (int) $insertGraphId > 0) {
										$graphTable->consistanceValueRange($insertChartId, $insertGraphId, $dataGraph['valuetype'],$instanceId);
									}
								}
							}
						}
						//End add preset graph
					} else {
						//insert chart when click make new preset
						$presetChartContructor->setChartName(Resources::_('DEFAULT_CHART_NAME'));
						$presetChartContructor->setFromDatetime($start);
						$presetChartContructor->setToDatetime($end);
						$presetChartContructor->setPreset($presetId);
						$insertPresetChartId   = $presetChartTable->save($presetChartContructor,$instanceId);
						if (isset($insertPresetChartId) && (int) $insertPresetChartId > 0) {
							$presetChartUpdate = $presetChartTable->findById($insertPresetChartId,$instanceId);
							$presetChartUpdate->setChartName(Resources::_('DEFAULT_CHART_NAME') . ' ' . sprintf('%03d', $insertPresetChartId));
							$presetChartTable->save($presetChartUpdate,$instanceId);
						}
						//End
						foreach ($arrHardware as $i=>$sensor) {
							$presetGraphContructor = new Shepherd_Model_PresetGraph();
							$presetGraphContructor->setPresetChart($insertPresetChartId);
							$presetGraphContructor->setColor('#' . $arrColors[$i]);
							$presetGraphContructor->setHardware($sensor);
							$presetGraphContructor->setGraphName($arrGraphNames[$i]);
							$presetGraphContructor->setValueType($arrValueTypes[$i]);
							$insertGraphId = $presetGraphTable->save($presetGraphContructor,$instanceId);
						}
						//Insert tables charts when click Make new preset
						$chartContructor->setPresetChartId($insertPresetChartId);
						$insertChartId   = $chartTable->save($chartContructor,$instanceId);
						if (isset($insertChartId) && (int) $insertChartId > 0) {
							$chartUpdate = $chartTable->findById($insertChartId,$instanceId);
							$chartUpdate->setChartName(Resources::_('DEFAULT_CHART_NAME') . ' ' . sprintf('%03d', $insertChartId));
							$chartTable->save($chartUpdate,$instanceId);
						}
						//End insert
					}
					$arrChartList[] = $insertChartId;
					$queryString = count($arrChartList) > 0 ? "?".'chart'. '=' . implode(',', $arrChartList) : '';
				} else {
					$listColor = $presetGraphTable->getColorListPresetGraphByChart($valueChart);
					foreach ($listColor as $listColor) {
						$arrCheckColor[] = $listColor['color'];
					}
					$chartId = $chartTable->getChartByGraph($valueChart);
					foreach ($arrHardware as $i=>$hr) {
						if(in_array("#".$arrColors[$i], $arrCheckColor)) {
							$color   = Sss_Ultility_Common::genRandomColor();
						} else {
							$color = $arrColors[$i];
						}
						$checkPresetGraphExists = $presetGraphTable->getPresetGraphByHardwareAndValueType($hr,$arrValueTypes[$i],$valueChart);
						if(empty($checkPresetGraphExists)) {
							$presetGraphContructor = new Shepherd_Model_PresetGraph();
							$presetGraphContructor->setPresetChart($valueChart);
							$presetGraphContructor->setColor('#' . $color);
							$presetGraphContructor->setHardware($hr);
							$presetGraphContructor->setGraphName($arrGraphNames[$i]);
							$presetGraphContructor->setValueType($arrValueTypes[$i]);
							$insertGraphId = $presetGraphTable->save($presetGraphContructor,$instanceId);
						}
					}
					//Add the graph of the other preset chart for select chart
					if ( $type == Sss_Ultility_CommonViewParamater::CHARTS ) {
						foreach ( $charts as $c ) {
							if ( $c['presetchartid'] != $valueChart ) {
								$getDataGraph = $presetGraphTable->getGraphListByChartId((int)$c['presetchartid']);
								foreach ( $getDataGraph as $dataGraph ) {
									$checkPresetGraphExists = $presetGraphTable->getPresetGraphByHardwareAndValueType($dataGraph['hardware'],$dataGraph['valuetype'],$valueChart);
									if (empty($checkPresetGraphExists)){
										$presetGraphContructor = new Shepherd_Model_PresetGraph();
										$presetGraphContructor->setPresetChart($valueChart);
										$presetGraphContructor->setColor($dataGraph['color']);
										$presetGraphContructor->setHardware($dataGraph['hardware']);
										$presetGraphContructor->setGraphName( $dataGraph['graphname']);
										$presetGraphContructor->setValueType($dataGraph['valuetype']);
										$insertGraphId = $presetGraphTable->save($presetGraphContructor,$instanceId);
									}
								}
							}
						}
					}
					//End add
					foreach($chartId as $c) {
						$check = in_array($c['chartid'], $arrChartList);
						if(!$check) {
							$arrChartList[] = $c['chartid'];
						}
					}
					$queryString = count($arrChartList) > 0 ? "?".'chart'. '=' . implode(',', $arrChartList) : '';
				}
				$isClose = 1;
			}
			$this->view->assign('isClosed', $isClose);
			$this->view->assign(Sss_Ultility_CommonViewParamater::LISTPRESET, $row);
			$this->view->assign('queryString',$queryString);
		}

		public function expandMergeGraphAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$defaultOvisNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_SHEPHERD_SYSTEM . $handle);
			$instanceId = $defaultOvisNamespace->dbShepherd;
			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$post       = $this->getRequest()->getPost();
			$chartId    = $this->getRequest()->getParam('chartid');
			$chartTable = new Shepherd_Model_Mapper_Chart();
			$chartContructor = new Shepherd_Model_Chart();
			$graphTable = new Shepherd_Model_Mapper_Graph();
			$isClosed = false;
			$updatedChartId = 0;
			$arrChart =  '';
			if (isset($post[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
				$isClosed = true;

				$strRemoveGraphIdList = $post['hdRemoveGraphs'];
				$strCopyGraphIdList   = $post['hdCopyGraphs'];
				$strGraphIds   = $post['hdGraphIds'];
				if (strlen($strRemoveGraphIdList) > 1) {
					$strRemoveGraphIdList = substr($strRemoveGraphIdList, 1, strlen($strRemoveGraphIdList) - 1);
				}
				$arrRemoveGraphs = explode(',', $strRemoveGraphIdList);
				if (strlen($strCopyGraphIdList) > 1) {
					$strCopyGraphIdList = substr($strCopyGraphIdList, 1, strlen($strCopyGraphIdList) - 1);
				}
				$arrCopyGraphs = explode(',', $strCopyGraphIdList);
				if ((!is_null($arrRemoveGraphs) && count($arrRemoveGraphs) > 0) || (!is_null($arrCopyGraphs) && count($arrCopyGraphs) > 0)) {
					$firstGraphId    = $post['cboDestinationArea'];
					$firstGraph = $graphTable->findById($firstGraphId,$instanceId);
					$toDateTime = strtotime(date(DATETIME_MYSQL_FORMAT));
					$fromDateTime = $end - 24*60*60;
					$timeRangeTypeValue = 3;
					if ($post['cboDestination'] == '') {
						if(strlen($strGraphIds) > 1){
							$strGraphIds =  substr($strGraphIds, 1, strlen($strGraphIds) - 1);
							$arrGraphIds =  explode(',', $strGraphIds);
							$graphIdDefault = $arrGraphIds[0];
							$graphDefault  = $graphTable->getGraphInformation($graphIdDefault);
							if($graphDefault){
								$chartDefault = $chartTable->getChartInformationDefault($graphDefault->chart);
								if($chartDefault){
									$fromDateTime =   $chartDefault->from_datetime;
									$toDateTime =   $chartDefault->to_datetime;
									$timeRangeTypeValue =  $chartDefault->time_range_type;
								}
							}
						}
						$firstGraph     = $graphTable->findById($firstGraphId,$instanceId);
						$chartContructor->setChartName(Resources::_('DEFAULT_CHART_NAME'));
						$chartContructor->setFromDatetime($fromDateTime);
						$chartContructor->setToDatetime($toDateTime);
						$chartContructor->setFromValue(0);
						$chartContructor->setToValue(0);
						$chartContructor->setCreatedDate(time());
						$chartContructor->setUpdatedDate(time());
						$chartContructor->setCreatedBy($userInformation->accountid);
						$chartContructor->setUpdatedBy($userInformation->accountid);
						$chartContructor->setHardware($firstGraph->hardware);
						$chartContructor->setTimeRangeType($timeRangeTypeValue);
						$chartContructor->setAverageValue(0);
						$chartContructor->setFilterValue(0);
						$chartContructor->setSmoothingValue(0);
						$updatedChartId = $chartTable->save($chartContructor,$instanceId);
						if(!is_null($updatedChartId) && $updatedChartId > 0) {
							$updateChart = $chartTable->findById($updatedChartId,$instanceId);
							$updateChart->setChartName(Resources::_('DEFAULT_CHART_NAME'). ' ' . sprintf('%03d', $updatedChartId));
							$chartTable->save($updateChart,$instanceId);
							if (!is_null($chartId)) {
								$chartId = $chartId == '' ? $updatedChartId : $chartId . ',' . $updatedChartId;
							}
						}
					} else {
						$updatedChartId = $post['cboDestination'];
					}
					if(!is_null($updatedChartId) && $updatedChartId > 0) {
						foreach ($arrRemoveGraphs as $rm) {
							$tmlRMGraph = $graphTable->findById($rm,$instanceId);
							if (isset($tmlRMGraph) && $tmlRMGraph !== false) {
								$tmlRMGraph->setChart($updatedChartId);
								$tmlRMGraph->setColor($tmlRMGraph->color);
								$tmlRMGraph->setGraphName($tmlRMGraph->graphname);
								$tmlRMGraph->setHardware($tmlRMGraph->hardware);
								$tmlRMGraph->setValueType($tmlRMGraph->valuetype);
								$graphTable->save($tmlRMGraph,$instanceId);
								$graphTable->consistanceValueRange($updatedChartId, $rm, $tmlRMGraph->valuetype,$instanceId);
							}
						}
						foreach ($arrCopyGraphs as $cp) {
							$tmlCPGraph = $graphTable->findById($cp,$instanceId);
							if (isset($tmlCPGraph) && $tmlCPGraph !== false) {
								$graphContructor = new Shepherd_Model_Graph();
								$graphContructor->setChart($updatedChartId);
								$graphContructor->setColor($tmlCPGraph->color);
								$graphContructor->setGraphName($tmlCPGraph->graphname);
								$graphContructor->setHardware($tmlCPGraph->hardware);
								$graphContructor->setValueType($tmlCPGraph->valuetype);
								$newGraphId = $graphTable->save($graphContructor,$instanceId);
								$graphTable->consistanceValueRange($updatedChartId, $newGraphId, $tmlCPGraph->valuetype,$instanceId);
							}
						}
					}
				}
				$charts = explode(',', $chartId);
				if($charts){
					foreach($charts as $c){
						$graphExistsChart = $graphTable->checkGraphExistChart($c);
						$checkChart = $chartTable->getInformationOfChartPreset($c);
						if($graphExistsChart == false) {
							if(empty($checkChart->presetchartid)) {

								$chartTable->deleteRow($c,$instanceId);
							}
						} else {
							if($arrChart == ''){
								$arrChart = $c . ',';
							}else{
								$arrChart .= $c . ',';
							}
						}
					}
				}
			}
			$arrCharts = array();
			if (!is_null($chartId) && $chartId != '') {
				$results = $chartTable->getChartListByChartIdList($chartId);
				if (isset($results)) {
					$arrCharts = $results;
				}
			}
			$arrGraphs = array();
			if (count($arrCharts) > 0) {
				$results = $graphTable->getGraphListByChart($arrCharts[0]['chartid']);
				if (isset($results)) {
					$arrGraphs = $results;
				}
			}
			if($arrChart != ''){
				$arrChart = substr($arrChart,0,strlen($arrChart) -1);
			}

			$this->view->assign('isClosed', $isClosed);
			$this->view->assign('arrGraphs', $arrGraphs);
			$this->view->assign('arrCharts', $arrCharts);
			$this->view->assign('chartid', $chartId);
		}

		public function printAllChartsAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);

			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$get            = $this->getRequest();
			$handle         = $get->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$chartId    = $this->getRequest()->getParam('chartid');
			$arrChartId = array();
			if (!is_null($chartId) && $chartId != '') {
				$arrChartId = explode(',', $chartId);
			}
			$this->view->assign('arrChartId', $arrChartId);
			//get breadscrumb
			$breadscrumbs = array(
			new Sss_CommonEntity_BreadScrumb(Resources::_('MONITORING_LOCALIZATION'), ''),
			new Sss_CommonEntity_BreadScrumb(Resources::_('GRAPHS'), '#'),
			new Sss_CommonEntity_BreadScrumb(count($arrChartId) > 1 ? Resources::_('PRINT_ALL_CHARTS') : Resources::_('PRINT_CHART'), '')
			);
			$this->view->assign('handle', $handle);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);
		}

		public function roomDetailAction()
		{

			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);

			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$roomid         = $this->getRequest()->getParam('room');
			$containerTable = new Shepherd_Model_Mapper_Container();
			if ((int) $roomid) {
				$strInfoContainer = $containerTable->getContainer($roomid);
				$this->view->assign('compressor', @$strInfoContainer->compressor);
				$this->view->assign('compressor_type', $strInfoContainer->compressor_type);
				$this->view->assign('lastest_revision', $strInfoContainer->lastest_revision);
				$this->view->assign('room_value', $strInfoContainer->room_value);
				$this->view->assign('isolation_material', $strInfoContainer->isolation_material);
				$this->view->assign('containername', $strInfoContainer->containername);
				$this->view->assign('roomstatistic', $this->getRoomStatisticInformation($roomid));
			}
		}

		public function chartItemAction()
		{

			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$chartTable   = new Shepherd_Model_Mapper_Chart();
			$getParams  = $this->getRequest();
			$chartId   = $getParams->getParam('chartid');
			$divId     = $getParams->getParam(Sss_Ultility_CommonViewParamater::DIVID);
			if(!empty($chartId)) { 
				$checkChartExists = $chartTable->checkChartExists($chartId);
			}
			$presetChartId   = $getParams->getParam('presetchart');
			$this->view->assign('chartid', $chartId);
			$this->view->assign('presetchart',$presetChartId);
			$this->view->assign(Sss_Ultility_CommonViewParamater::DIVID,$divId);
			$this->view->assign('checkChartExists',$checkChartExists);
		}

		public function ajaxChartAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$getParams  = $this->getRequest();
			$post       = $this->getRequest()->getPost();
			$deleteGraph = $getParams->getParam(Sss_Ultility_CommonViewParamater::DELETE_GRAPH);
			$chartTable   = new Shepherd_Model_Mapper_Chart();
			$graphTable   = new Shepherd_Model_Mapper_Graph();
			$fourtsDataTable    = new Shepherd_Model_Mapper_PostData();
			$lemDataTable    = new Application_Model_Mapper_LEMData();
			$hardwareTable   = new Application_Model_Mapper_Hardware();
			$chartSessionTable   = new Shepherd_Model_Mapper_ChartSession();
			$instanceTable  = new Application_Model_Mapper_Instance();
			$presetGraphTable = new Shepherd_Model_Mapper_PresetGraph();
			$presetChartTable = new Shepherd_Model_Mapper_PresetChart();
			$presetTable      = new Shepherd_Model_Mapper_Preset();
			$chartId   = $getParams->getParam('chartid'); 
			$divId = $getParams->getParam(Sss_Ultility_CommonViewParamater::DIVID); 
			$sessionQueryString = new Zend_Session_Namespace('queryString');
			$queryString = $sessionQueryString->queryString;
			$checkChartExists = $chartTable->checkChartExists($chartId);
			if($checkChartExists != 0 ) {
				$arrChartList    = array();
				if ($queryString != '') {
					$arrChartList = explode(',', $queryString);
				}
				$params = $this->_request->getParams();
				$instance = $instanceTable->getInstanceByHandle($handle);
				$instanceId = $instance->instanceid;
				$chart = $chartTable->getChartInformation($chartId, $userInformation->accountid);
				$this->view->assign('fromTimeOld',$chart->from_datetime);
				$this->view->assign('toTimeOld',$chart->to_datetime);
				if(!empty($chart->presetchartid)) {
					$dataName = $presetChartTable->getByNameOfPreset((int)$chart->presetchartid);
				}
				if ((int)$deleteGraph > 0) {
					$urlRequest = $getParams->getParam('chart');
					if(!empty($chart->presetchartid)) { 
						$presetGraphTable->deleteRow((int) $deleteGraph,null,$instanceId);
						$checkGraph = $presetGraphTable->checkPresetGraphExistChart((int)$chart->presetchartid);
						if ($urlRequest != '') {
							$arrChartList = explode(',', $urlRequest);
						}
						if($checkGraph == false) {



							$presetChartTable->deleteRow((int) $chart->presetchartid,$instanceId);
							$chartSessionTable->deleteRow(null,array('chart = ?' => $chartId),$instanceId);
							$chartTable->deleteRow($chartId,$instanceId);
							$checkPreset = $presetChartTable->checkPresetChart($dataName[0]['presetid']);
							if((int)$checkPreset->count == 0) {
								$presetTable->deleteRow((int) $dataName[0]['presetid'],$instanceId);
							}
							if (count($arrChartList) > 0) {
								$key = array_search($chartId, $arrChartList);
								unset($arrChartList[$key]);
							}
						}
					} else { 
						$graphTable->deleteRow($deleteGraph,null,$instanceId);
						$checkGraph = $graphTable->checkGraphExistChart($chartId);
						if ($urlRequest != '') {
							$arrChartList = explode(',', $urlRequest);
						}
						if($checkGraph == false){
							$chartSessionTable->deleteRow(null,array('chart = ?' => $chartId),$instanceId);
							$chartTable->deleteRow($chartId,$instanceId);
							if (count($arrChartList) > 0) {
								$key = array_search($chartId, $arrChartList);
								unset($arrChartList[$key]);
							} 
						}
					}
					$queryString     = count($arrChartList) > 0 ?  'chart' . '=' . implode(',', $arrChartList) : '';
					$this->redirect(Resources::_('DELETE_GRAPH_SUCCESSFULL'), $this->view->url(array(
					Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
					Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
					)) . '?' . $queryString);
				}
				if (isset($post[Sss_Ultility_CommonViewParamater::BTN_SAVE])) {
					if(!empty($chart->presetchartid)) {
						$presetChart = (int) $chart->presetchartid;
						$graphs           = $presetGraphTable->getGraphListByPresetChart($presetChart);
					} else {
						$graphs           = $graphTable->getGraphListByChart((int) $chartId);
					}
					//get value chart by id
					$updatedChart = $chartTable->findById($chartId,$instanceId);
					if($post['isVariousGraph'] == '1') {
						$graphIndex = $post['graphIndex'];
						$unicode = $graphs[$graphIndex-1]['unitcode'];
						$updateFromValue = $post['txtFromValue'] == '' ? 0 : $post['txtFromValue'];
						$updateToValue = $post['txtToValue'] == '' ? 0 : $post['txtToValue'];
						foreach ($graphs as $gr) {
							if($gr['unitcode'] == $unicode) {
								if(!empty($chart->presetchartid)) {
									$updateGraph = $presetGraphTable->findById($gr['graphid'],$instanceId);
									$updateGraph->setFromValue($updateFromValue);
									$updateGraph->setToValue($updateToValue);
									$presetGraphTable->save($updateGraph,$instanceId);
								} else {
									$updateGraph = $graphTable->findById($gr['graphid'],$instanceId);
									$updateGraph->setFromValue($updateFromValue);
									$updateGraph->setToValue($updateToValue);
									$graphTable->save($updateGraph,$instanceId);
								}
							}
						}
					} else {
						$fromValueUpdate = $post['txtFromValue'] == '' ? 0 : $post['txtFromValue'];
						$toValueUpdate = $post['txtToValue'] == '' ? 0 : $post['txtToValue'];
						$updatedChart->setFromValue($fromValueUpdate);
						$updatedChart->setToValue($toValueUpdate);
						$updatedChart->setUpdatedBy($userInformation->accountid);
						$updatedChart->setUpdatedDate(strtotime('now'));
					}
					if ($post['txtFromDateTime'] != '' && $post['txtToDateTime']!= '') {
						$updatedChart->setFromDatetime(Sss_Ultility_Common::getDateTimeNumber($post['txtFromDateTime']));
						$updatedChart->setToDatetime(Sss_Ultility_Common::getDateTimeNumber($post['txtToDateTime']));
						$updatedChart->setTimeRangeType(3);
					}
					if (isset($post['chkAverage']) && $post['chkAverage'] == "true" ) {
						$updatedChart->setAverageValue(1);
					} else {
						$updatedChart->setAverageValue(0);
					}

					if (isset($post['chkFilterData']) && $post['chkFilterData'] == "true" ) {
						$updatedChart->setFilterValue(1);
					} else {
						$updatedChart->setFilterValue(0);
					}
					if (isset($post[Sss_Ultility_CommonViewParamater::SMOOTHING]) && $post[Sss_Ultility_CommonViewParamater::SMOOTHING] == "true" ) {
						$updatedChart->setSmoothingValue(1);
					} else {
						$updatedChart->setSmoothingValue(0);
					}
					$chartTable->save($updatedChart,$instanceId);
					if(!empty($chart->presetchartid)) {
						if ($post['txtFromDateTime'] != '' && $post['txtToDateTime']!= '') {
							$updatedPresetChart = $presetChartTable->findById($chart->presetchartid,$instanceId);
							$updatedPresetChart->setFromDatetime(Sss_Ultility_Common::getDateTimeNumber($post['txtFromDateTime']));
							$updatedPresetChart->setToDatetime(Sss_Ultility_Common::getDateTimeNumber($post['txtToDateTime']));
							$presetChartTable->save($updatedPresetChart,$instanceId);
						}
					}
				}
				if (isset($post['hdChartAction' . $chartId])) {
					if (($post['hdChartAction' . $chartId]) == 1) {
						$urlRequest = $post['urlRepquest'. $chartId];
						if(!empty($chart->presetchartid)) { 
							$chartSessionTable->deleteRow(null,array('chart = ?' => $chartId),$instanceId);
							$chartTable->deleteRow($chartId,$instanceId);
							$presetChartTable->deleteRow((int)$chart->presetchartid,$instanceId);
							$presetGraphTable->deleteRow(null,array('presetchart = ?' => (int)$chart->presetchartid),$instanceId);
							$checkPreset = $presetChartTable->checkPresetChart($dataName[0]['presetid']);
							if((int)$checkPreset->count == 0) {
								$presetTable->deleteRow((int) $dataName[0]['presetid'],$instanceId);
							}
						} else {
							$chartSessionTable->deleteRow(null ,array('chart = ?' => $chartId),$instanceId);
							$graphTable->deleteRow(null,array('chart = ?' => $chartId),$instanceId);
							$chartTable->deleteRow($chartId,$instanceId); 
						}
						if ($urlRequest != '') {
							$arrChartList = explode(',', $urlRequest);
						}
						if (count($arrChartList) > 0) {
							$key = array_search($chartId, $arrChartList);
							unset($arrChartList[$key]);
						} 
						$this->redirect(Resources::_('DELETE_CHART_SUCCESSFULL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
						)) . (count($arrChartList) > 0 ? '?chart=' . implode(',', $arrChartList) : ''));
					} elseif (($post['hdChartAction' . $chartId]) == 2) {
						$updatedPresetChart = $chartSessionTable->findById($chartId,'chart',$instanceId);
						if($updatedPresetChart != null) {
							$updatedPresetChart->setRemoved(1);
							$chartSessionTable->save($updatedPresetChart,$instanceId);
						}
						if (count($arrChartList) > 0) {
							$key = in_array($chartId, $arrChartList);
							if($key) {
								unset($arrChartList[$key]);
							}
						}
						$this->redirect(Resources::_('REMOVE_CHART_SUCCESSFULL'), $this->view->url(array(
						Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
						Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
						)) . (count($arrChartList) > 0 ? '?chart=' . implode(',', $arrChartList) : ''));
					}
				}
				$chart = $chartTable->getChartInformation($chartId, $userInformation->accountid);
				if (!$chart)
					return;
				$fromDateTime = null; // ('2011-08-01 00:00');
				$toDateTime   = null; //('2011-08-01 01:00');
				$fromValue    = 0;
				$toValue      = 0;
				if (isset($chart)) {
					if ((int) $chart->time_range_type == 1) {
						$toDateTime   = date(DATETIME_MYSQL_FORMAT);
						$fromDateTime = new DateTime($toDateTime);
						$fromDateTime = (array) $fromDateTime->modify('-1 hour');
						$fromDateTime = $fromDateTime['date'];
					} elseif ((int) $chart->time_range_type == 2) {
						$toDateTime   = date(DATETIME_MYSQL_FORMAT, strtotime('now'));
						$fromDateTime = date(DATETIME_SORT_MYSQL_FORMAT, strtotime('now'));
					} else {
						$toDateTime   = date(DATETIME_MYSQL_FORMAT, $chart->to_datetime);
						$fromDateTime = date(DATETIME_MYSQL_FORMAT, $chart->from_datetime);
					}

					if ($chart->from_value != $chart->to_value) {
						$fromValue =  $chart->from_value;
						$toValue   =  $chart->to_value;
					}
				}
				if(!empty($chart->presetchartid)) {
					$presetChart = (int) $chart->presetchartid;
					$graphs           = $presetGraphTable->getGraphListByPresetChart($presetChart);
				} else {
					$graphs           = $graphTable->getGraphListByChart((int) $chartId);
				}
				$arrayGraphValues = array();
				$arrayCheckData = array();

				$variousGraph = array();
				$isVariousGraph = false;
				if (isset($graphs) && count($graphs) > 0) {
					foreach ($graphs as $gr) {
						if	(!in_array($gr['unitcode'], $variousGraph)) {
							$variousGraph[] = $gr['unitcode'];
						}
					}
					$isVariousGraph = count($variousGraph) > 1 ? true : false;
					$totalValue = 0;
					$timeStartGetData = time();
					foreach ($graphs as $k=>$gr) {
						$crrHardwareId = (int) $gr['hardware'];
						$crrValueType = (int) $gr['valuetype'];
						if ($isVariousGraph) {
							$toValue = is_null($gr['to_value']) ? 0 : $gr['to_value'];
							$fromValue = is_null($gr['from_value']) ? 0 : $gr['from_value'];
						}
						$column = $fourtsDataTable->getColumn($crrValueType);
						if($column != null){
							$fourtsDataTable->checkEsixtedColumns($column,$instance->instanceid);
						}
						$arrayData = array(
								'from_value' => $fromValue,
								'to_value' => $toValue,
								'from_datetime' => $fromDateTime,
								'to_datetime' => $toDateTime,
								'unitcode' => $gr['unitcode'],
								'average_value' => $chart->average_value,
								'filter_value' => $chart->filter_value
						);
						if ($gr['vendor'] == 2) { // LEM vendor
							$currGraphValues = $lemDataTable->getDataByHardware($crrHardwareId, $crrValueType, $arrayData);
							$getValueMaxMin = $lemDataTable->getDataMinMaxByHardware($crrHardwareId, $crrValueType, $arrayData);
						} else { // 4TS vendor 
							$currGraphValues = $fourtsDataTable->getDataByHardware($crrHardwareId, $crrValueType, $arrayData);
							$getValueMaxMin = $fourtsDataTable->getDataMaxMinByHardware($crrHardwareId, $crrValueType, $arrayData);
						}

						if (!is_null($currGraphValues) && isset($currGraphValues['unitcode'])) { 
							$graphs[$k]['unitcode'] = $currGraphValues['unitcode'];
							$arrayGraphValues[] = $currGraphValues['value'];
							$arrayCheckData[$gr['graphid']] = count($currGraphValues['value']);
							//total point of chart when write log file 
							$totalValue += count($currGraphValues['value']);
						}
						$fromValue    = 0;
						$toValue      = 0;
						$arrValueType = $hardwareTable->getlastValue($crrHardwareId,$crrValueType, $instance->instanceid);
						$typeCode='';
						if(count($arrValueType) > 0){
							$gr[Sss_Ultility_CommonViewParamater::VALUETYPE] = $arrValueType[0];
							$gr[Sss_Ultility_CommonViewParamater::CREATED_DATE_MAX] = $arrValueType[1];
							$gr['unitcode'] = $arrValueType[2];
							$typeCode =  $arrValueType[4];
						}
						$gr[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_OFFLINE;
						if(Sss_Ultility_Common::checkHardwareOnline($arrValueType[1])) {
							$gr[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_ONLINE;
						}
						if(Sss_Ultility_Common::checkHardwareBadConnection($gr['hardware'],$gr['vendor'],$typeCode)) {
							$gr[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_BAD_CONNECTION;
						}
						if(Sss_Ultility_Common::checkHardwareOfline($arrValueType[1])) {
							$gr[Sss_Ultility_CommonViewParamater::STATUS] = Sss_Ultility_Setting::HARDWARE_OFFLINE;
						}
						$gr[Sss_Ultility_CommonViewParamater::GETVALUEMAX] = $getValueMaxMin->valueMax;
						$gr[Sss_Ultility_CommonViewParamater::GETVALUEMIN] = $getValueMaxMin->valueMin;
						$graph[]= $gr;
					}
				}
				$timeEndGetData = time();
				$checkChartExists = $chartTable->checkChartExists($chartId);
				$this->view->assign('checkChartExists',$checkChartExists);
				$this->view->assign('arrayCheckData', $arrayCheckData);
				$this->view->assign('isVariousGraph', $isVariousGraph);
				$this->view->assign(Sss_Ultility_CommonViewParamater::QUERY_STRING, $queryString);
				$this->view->assign(Sss_Ultility_CommonViewParamater::SHOW_OPTION, is_null($chart->showed) ? false : $chart->showed);
				$print = ($this->getRequest()->getParam('print') || $this->getRequest()->getParam('popup'));
				$this->view->assign('print', $print);
				$this->view->assign('arrayGraphValues', $arrayGraphValues);
				$this->view->assign('chart', $chart);
				$this->view->assign('graphs', $graph);
				$this->view->assign('datetype', $dateType);
				$this->view->assign('dataName',$dataName);
				$this->view->assign('chartid', $chartId);
				$this->view->assign('instanceid',$instanceId);
				$this->view->assign('chartData',$chartTable);
				$this->view->assign(Sss_Ultility_CommonViewParamater::DIVID,$divId);
				$this->view->assign("fromDateTime",$params['txtFromDateTime']);
				$this->view->assign("toDateTime",$params['txtToDateTime']);
				$this->view->table = new Application_Model_Mapper_Hardware();
				$ajax   = $getParams->getParam(Sss_Ultility_CommonViewParamater::AJAXDISABLELAYOUT);
				//write log to check time load chart
				$infoChart = 'chartId:'.$chartId;
				$infoTotal = 'Totalpoint:'.$totalValue;
				$time = 'Time get data:'.($timeEndGetData - $timeStartGetData).' seconds';
				$info = "\n\t".$infoChart."\n\t".$infoTotal."\n\t".$time;
				$this->view->assign('info',$info);
				//end write
				if(!isset($ajax)){
					$this->_helper->layout->disableLayout();
				}
			} else { 
				$this->_helper->layout->disableLayout();
			}
		}

		public function showHardwareInformationAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);

			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$getParams     = $this->getRequest();
			$hardwareId    = $getParams->getParam('hardwareid');
			$hardwareTable = new Application_Model_Mapper_Hardware();

			$hardware = $hardwareTable->getHardwareToShowInformation((int) $hardwareId);
			$this->view->assign('hardware', $hardware);
		}

		public function quickAddNewGraphAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$defaultOvisNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_SHEPHERD_SYSTEM . $handle);
			$instanceId = $defaultOvisNamespace->dbShepherd;

			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$getParams = $this->_request->getParams();
			$chartTable      = new Shepherd_Model_Mapper_Chart();
			$chartContructor = new Shepherd_Model_Chart();
			$graphTable      = new Shepherd_Model_Mapper_Graph();
			$queryString     = isset($getParams['chart']) ? $getParams['chart'] : '';
			$arrChartList    = array();
			if ($queryString != '') {
				$arrChartList = explode(',', $queryString);
			}

			$sensor    = $getParams[Sss_Ultility_CommonViewParamater::SENSORT_ID];
			$vt        = $getParams[Sss_Ultility_CommonViewParamater::VALUE_ID];
			$color     = $getParams[Sss_Ultility_CommonViewParamater::COLOR_LIST];
			$graphName     = $getParams[Sss_Ultility_CommonViewParamater::GRAPH_NAME_LIST];


			if ($sensor == '' || $vt == '' || $color == '' || $graphName == '') {
				$queryString = count($arrChartList) > 0 ? '?chart=' . implode(',', $arrChartList) : '';
				$this->redirect('', $this->view->url(array(
				Sss_Ultility_CommonViewParamater::CONTROLLER => $this->view->controllerName,
				Sss_Ultility_CommonViewParamater::ACTION => 'graphs'
				)) . $queryString);
			}

			$arrSensors = explode(',', $sensor);
			$arrVt = explode(',', $vt);
			$arrColors = explode(',', $color);
			$arrGraphNames = explode(',', $graphName);
			$timeRangeTypeValue = 3;
			$end = strtotime(date(DATETIME_MYSQL_FORMAT));
			$start = $end - 24*60*60;
			$chartContructor->setChartName(Resources::_('DEFAULT_CHART_NAME'));
			$chartContructor->setFromDatetime($start);
			$chartContructor->setToDatetime($end);
			$chartContructor->setFromValue(0);
			$chartContructor->setToValue(0);
			$chartContructor->setCreatedBy($userInformation->accountid);
			$chartContructor->setUpdatedBy($userInformation->accountid);
			$chartContructor->setCreatedDate(time());
			$chartContructor->setUpdatedDate(time());
			$chartContructor->setHardware($arrSensors[0]);
			$chartContructor->setTimeRangeType($timeRangeTypeValue);
			$chartContructor->setAverageValue(0);
			$chartContructor->setFilterValue(0);
			$chartContructor->setSmoothingValue(0);
			$insertChartId   = $chartTable->save($chartContructor,$instanceId);
			try {
				if (isset($insertChartId) && (int) $insertChartId > 0) {
					$updateChart = $chartTable->findById($insertChartId,$instanceId);
					$updateChart->setChartName(Resources::_('DEFAULT_CHART_NAME') . ' ' . sprintf('%03d', $insertChartId));
					$chartTable->save($updateChart,$instanceId);
					$arrChartList[] = $insertChartId;
					$queryString = count($arrChartList) > 0 ? '?chart=' . implode(',', $arrChartList) : '';
					//End save
					foreach ($arrSensors as $i=>$sensor) {
						$graphContructor = new Shepherd_Model_Graph();
						$graphContructor->setGraphName($arrGraphNames[$i]);
						$graphContructor->setChart($insertChartId);
						$graphContructor->setColor('#' . $arrColors[$i]);
						$graphContructor->setHardware($sensor);
						$graphContructor->setValueType($arrVt[$i]);
						$graphTable->save($graphContructor,$instanceId);
					}
					echo $insertChartId;
				}
			} catch (Exception $e) {
					Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
			}
			die;
		}

		public function viewChartAction()
		{

			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);

			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$get            = $this->getRequest();
			$handle         = $get->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$chartId    = $this->getRequest()->getParam('chartid');
			$arrChartId = array();
			if (!is_null($chartId) && $chartId != '') {
				$arrChartId = explode(',', $chartId);
			}
			$this->view->assign('arrChartId', $arrChartId);
			$this->view->assign('handle', $handle);
		}

		public function graphsExportCsvAction()
		{
			set_time_limit(1000);
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());

			$chartTable   = new Shepherd_Model_Mapper_Chart();
			$graphTable   = new Shepherd_Model_Mapper_Graph();
			$presetGraphTable = new Shepherd_Model_Mapper_PresetGraph();
			$fourtsDataTable    = new Shepherd_Model_Mapper_PostData();
			$lemDataTable    = new Application_Model_Mapper_LEMData();
			$instanceTable  = new Application_Model_Mapper_Instance();
			$chartId    = $this->getRequest()->getParam('chartid');
			$csv = '';
			$arrChartId = array();
			if (!is_null($chartId) && $chartId != '') {
				$arrChartId = explode(',', $chartId);
			}









			$arrCSVChartNames = array();
			$arrCSVGrapNames = array();
			$arrCSVData = array();
			$arrCSVSerialNumber  = '';
			$arrCSVSerialTitle = '';
			$arrCSVUnitCode = Resources::_('UNIT');
			foreach ($arrChartId as $chartId) {
				$chart = $chartTable->getChartInformation($chartId, $userInformation->accountid);
				if (!$chart)
					return;
				$arrCSVChartNames[] 	=  $chart->chartname;
				$csv .=  $chart->chartname . "\n";
				$fromDateTime = null; // ('2011-08-01 00:00');
				$toDateTime   = null; //('2011-08-01 01:00');
				$fromValue    = 0;
				$toValue      = 0;
				if (isset($chart)) {
					if ((int) $chart->time_range_type == 1) {
						$toDateTime   = date(DATETIME_MYSQL_FORMAT);
						$fromDateTime = new DateTime($toDateTime);
						$fromDateTime = (array) $fromDateTime->modify('-1 hour');
						$fromDateTime = $fromDateTime['date'];
					} elseif ((int) $chart->time_range_type == 2) {
						$toDateTime   = date(DATETIME_MYSQL_FORMAT, strtotime('now'));
						$fromDateTime = date(DATETIME_SORT_MYSQL_FORMAT, strtotime('now'));
					} else {
						$toDateTime   = date(DATETIME_MYSQL_FORMAT, $chart->to_datetime);
						$fromDateTime = date(DATETIME_MYSQL_FORMAT, $chart->from_datetime);
					}
					if ($chart->from_value != $chart->to_value) {
						$fromValue = (int) $chart->from_value;
						$toValue   = (int) $chart->to_value;
					}
				}
				if(!empty($chart->presetchartid)) {
					$presetChart = (int) $chart->presetchartid;
					$graphs           = $presetGraphTable->getGraphListByPresetChart($presetChart);
				} else {
					$graphs           = $graphTable->getGraphListByChart((int) $chartId);
				}
				$arrayGraphValues = array();
				$variousGraph = array();
				$isVariousGraph = false;
				$array1 = array();
				$array2 = array();
				if (isset($graphs) && count($graphs) > 0) {
					foreach ($graphs as $gr) {
						if	(!in_array($gr['unitcode'], $variousGraph)) {
							$variousGraph[] = $gr['unitcode'];
						}
					}
					$isVariousGraph = count($variousGraph) > 1 ? true : false;
					$indexGraph = false;
					$graphName = '';
					$indexFirst = 0;
					$indexFirst1 = 0;
					foreach ($graphs as $gr) {
						$newArray = array();
						$newArrayFirst = array();
						$crrHardwareId = (int) $gr['hardware'];
						$serialNumber =  $gr['serial_number'];
						$serialTitle =  Resources::_('SENSORID');
						$crrValueType = (int) $gr['valuetype'];
						if ($isVariousGraph) {
							$toValue = is_null($gr['to_value']) ? 0 : $gr['to_value'];
							$fromValue = is_null($gr['from_value']) ? 0 : $gr['from_value'];
						}
						$column = $fourtsDataTable->getColumn($crrValueType);
						if($column != null){
							$fourtsDataTable->checkEsixtedColumns($column,$instance->instanceid);
						}
						$arrayData = array(
								'from_value' => $fromValue,
								'to_value' => $toValue,
								'from_datetime' => $fromDateTime,
								'to_datetime' => $toDateTime,
								'unitcode' => $gr['unitcode'],
								'average_value' => $chart->average_value,
								'filter_value' => $chart->filter_value
						);
						if ($gr['vendor'] == 2) { // LEM vendor

							$currGraphValues = $lemDataTable->getDataByHardware($crrHardwareId, $crrValueType,$arrayData);
						} else { // 4TS vendor

							$currGraphValues = $fourtsDataTable->getDataByHardware($crrHardwareId, $crrValueType,$arrayData);
						}
						if(count($graphs) == 1) {
							$arrayGraphValues[$gr['graphname']] =  $currGraphValues['value'];
						} else {
							if(count($array1) > 0){
								$array2 = $currGraphValues['value'];
								if($indexGraph){
									foreach($array1 as $key1=>$arr1){
										$newArrayFirst[date_format(date_create($arr1['created_date']),DATETIME_MYSQL_FORMAT)] = array(
										'created_date'=>date_format(date_create($arr1['created_date']),DATETIME_MYSQL_FORMAT),
										'value'=>$arr1['value'],
										);
									}
									foreach($array2 as $key2=>$arr2){
										if(array_key_exists(date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT), $newArrayFirst)){
											$newArrayFirst[date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT)] = array(
											'created_date'=>date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT),
											'value'=>$newArrayFirst[date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT)]['value'],
											);
										}else{
											$newArrayFirst[date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT)] = array(
											'created_date'=>date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT),
											'value'=>'',
											);
										}
									}
								}
								$indexFirst1 ++;
								if($indexFirst1 > 1){
									foreach($array1 as $key1=>$arr1){
										$newArray[$arr1['created_date']] = array(
										'created_date'=>$arr1['created_date'],
										'value'=>'',
										);
									}
								} else {
									foreach($array1 as $key1=>$arr1){
										$newArray[date_format(date_create($arr1['created_date']),DATETIME_MYSQL_FORMAT)] = array(
										'created_date'=>date_format(date_create($arr1['created_date']),DATETIME_MYSQL_FORMAT),
										'value'=>'',
										);
									}
								}
								foreach($array2 as $key2=>$arr2){
									if(array_key_exists(date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT), $newArray)){
										$newArray[date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT)] = array(
										'created_date'=>date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT),
										'value'=>$arr2['value']
										);
									} else {
										$newArray[date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT)] = array(
										'created_date'=>date_format(date_create($arr2['created_date']),DATETIME_MYSQL_FORMAT),
										'value'=>$arr2['value'],
										);
									}
								}
							} else {
								$indexGraph = true;
								$graphName = $gr['graphname'];
							}

							if(!is_null($newArrayFirst)) {
								if($indexGraph)
								{
									$newArray2  = array();
									sort($newArrayFirst);
									foreach($newArrayFirst as $key3=>$arr3){
										$newArray2[] = $arr3;
									}
									$arrayGraphValues[$graphName] = $newArray2;
									if(count($newArray2) > 0){
										$indexGraph = false;
									}
								}
							}
							if (!is_null($newArray)) {
								$newArray1 = array();
								sort($newArray);
								foreach($newArray as $key3=>$arr3){
									$newArray1[] = $arr3;
								}
								$arrayGraphValues[$gr['graphname']] = $newArray1;
							}
							if($indexFirst <= 0){
								$array1  =   $currGraphValues['value'];
							}else{
								$array1  =   $newArray1;
							}
							$indexFirst++;
						}
						$arrCSVUnitCode .= ',' . $currGraphValues['unitcode'];
						$arrCSVSerialTitle .= ',' . $serialTitle;
						$arrCSVSerialNumber .=  ',' . $serialNumber;
					}
					$arrCSVUnitCode  = $arrCSVUnitCode . ',' . Resources::_('UNIT');
					$arrCSVSerialNumber = $arrCSVSerialNumber . '_';
					$arrCSVSerialTitle = $arrCSVSerialTitle . '_';
					$arrCSVGraphValues = array();
					foreach ($arrayGraphValues as $name=>$graphVal) {
						if (!empty($graphVal)) {
							$arrCSVGraphValues[Resources::_('DATE_AND_TIME')] = null;
							foreach($graphVal as $r){
								$tmpVal = '';
								$tmpDate = $r['created_date'];
								if (!is_null($r['value'])) {
									$tmpVal = explode(',', $r['value']);
									if (count($tmpVal) == 2) {
										$tmpVal = $tmpVal[1];
										$tmpVal = substr($tmpVal, 0, strlen($tmpVal) - 1);
									}else{
										$tmpVal    = ';';
									}
								}else{
									$tmpVal    = ';';
								}
								$arrCSVGraphValues[Resources::_('DATE_AND_TIME')][] = date_format(date_create($tmpDate),DATETIMEFORMAT);
								$arrCSVGraphValues[$name][] = $tmpVal;
							}
						}
					}
					foreach ($arrCSVGraphValues as $graphName=>$grpVal) {
						$arrCSVGrapNames[] = $graphName;
						$arrCSVData[] =  $grpVal;
					}
					$arrCSVGraphValues = array();
					$arrayGraphValues = array();
				}
			}
			//End process foreach array charts
			$count = 0;
			foreach ($arrCSVData as $name=>$graphVal) {
				if($name != Resources::_('DATE_AND_TIME')){
					if($count == 0){
						$count = count($graphVal);
					}
					if($count < count($graphVal)){
						$count = count($graphVal);
					}
				}
			}
			$arrData  = array();
			$indexTemp = 0;
			for($i=0; $i < $count; $i++){
				$value = '';
				foreach($arrCSVData as $c){
					if($c[$i] == ''){
						$c[$i] = ';';
					}
					if($value == ''){
						$value = $c[$i];
					}else{
						$value = $value . ','. $c[$i];
					}
				}
				$arrData[] = $value ;
				$indexTemp ++;
			}
			$count = 0;
			$arrCSVSerialTitle = (empty($arrCSVSerialTitle) ? '' :  explode('_', $arrCSVSerialTitle));
			foreach($arrCSVGrapNames as $g){
				if($g == Resources::_('DATE_AND_TIME')){
					$charName .= Resources::_('TITLE_CHART_NAME') . $arrCSVSerialTitle[$count] . ',';
					$count ++;
				}else{
					$charName .= "";
				}
			}
			$count = 0;
			$arrCSVSerialNumber = (empty($arrCSVSerialNumber) ? '' :  explode('_', $arrCSVSerialNumber));
			foreach($arrCSVGrapNames as $g){
				if($g == Resources::_('DATE_AND_TIME')){
					$charNameList .= $arrCSVChartNames[$count] . $arrCSVSerialNumber[$count] . ',';
					$count ++;
				}else{
					$charNameList .= "";
				}
			}
			$grapNameList =  (empty($arrCSVGrapNames) ? '' : '' . implode(",", $arrCSVGrapNames)) ;
			$valueList = (empty($arrData) ? '' : "\n" . implode("\n", $arrData)).',' ;
			$valueList = str_replace(';,',',',$valueList);
			$valueList = substr($valueList,0,strlen($valueList)-1);
			$arrCSVUnitCode = substr($arrCSVUnitCode,0,strlen($arrCSVUnitCode)-5);
			$charName = substr($charName,0,strlen($charName)-1);
			$charNameList = substr($charNameList,0,strlen($charNameList)-1);
			echo $csv = $charName . "\n" . $charNameList . "\n" . $arrCSVUnitCode ."\n" . $grapNameList."\n".$valueList ;
			header("Content-type: application/vnd.ms-excel");
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-disposition: csv; filename=" . Resources::_('GRAPH_EXPORT_FILE') . date("Y-m-d-H-i") . ".csv; size=" . strlen($csv));
			header("Content-Transfer-Encoding: binary ");
		}

		public function geomappingAction()
		{

			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			
			// get session instance Id
			$defaultOvisNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_SHEPHERD_SYSTEM . $handle);
			$instanceId = $defaultOvisNamespace->dbShepherd;

			//check permission
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GEOMAPPING, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/inventory/stock-location-detail");
			}
			//get breadscrumb
			$breadscrumbs = array(
			new Sss_CommonEntity_BreadScrumb($this->_menuName, ''),
			new Sss_CommonEntity_BreadScrumb('Geomapping', '#')
			);
			$this->view->assign(Sss_Ultility_CommonViewParamater::BREADSCRUMBS, $breadscrumbs);

			$paramItemId     = $this->_request->getParam('itemid', 'underfine');
			$paramShipmentId = $this->_request->getParam('shipmentid', 'underfine');
			//get parameter hardware
			$paramHardwareId = $this->_request->getParam('hardwareid', Sss_Ultility_CommonViewParamater::UNDERFINE);
			if ($paramItemId > 0) {
				//get address from item table to show on map
				$itemTable    = Sss_Service_Locator::getInstance()->getService($this->_getShepherdTable('Item'));
				$dataItemById = $itemTable->getItemById($paramItemId);
				$s = "var markers =[";
				$s .= "{";
				$s .= "'name':'" . $dataItemById->itemname . "',";
				$s .= "'address':'" . $dataItemById->address . "',";
				$s .= "'post':'" . $dataItemById->postcode . "',";
				$s .= "'city':'" . $dataItemById->city . "',";
				$s .= "'country':'" . $dataItemById->country . "',";
				$s .= "'created_date':'" . date(DATETIMEFORMAT, $dataItemById->created_date) . "',";
				$s .= "'updated_date':'" . ($dataItemById->updated_date > 0 ? date(DATETIMEFORMAT, $dataItemById->updated_date) : '0') . "'";
				$s .= "},";
				$s .= "];";
			} elseif ($paramShipmentId > 0) {
				//get address from shipment table to show on map
				$stocklocationTable = new Application_Model_Mapper_StockLocation();
				$dataStocklocationById = $stocklocationTable->getListFromShipment($paramShipmentId,$instanceId);
				$s = "var markers =[";
				foreach ($dataStocklocationById as $dataStock) {
					$s .= "{";
					$s .= "'locationid':'" . $dataStock['stocklocationid'] . "',";
					$s .= "'name':'" . $dataStock['shipmentname'] . "',";
					$s .= "'address':'" . $dataStock['address'] . "',";
					$s .= "'post':'" . $dataStock['postcode'] . "',";
					$s .= "'city':'" . $dataStock['city'] . "',";
					$s .= "'country':'" . $dataStock['country'] . "',";
					$s .= "'ship_date':'" . date($dataStock['ship_date']) . "',";
					$s .= "'internal_ref':'" . $dataStock['internal_ref'] . "',";
					$s .= "'reference_number':'" . $dataStock['reference_number'] . "',";
					$s .= "'supplier_ref':'" . $dataStock['supplier_ref'] . "'";
					$s .= "},";
				}
				$s .= "];";
			} else if($paramHardwareId != Sss_Ultility_CommonViewParamater::UNDERFINE){

					//get address to show on map        
					$hardwareTable = new Application_Model_Mapper_Hardware();
					$dataHardwareById = $hardwareTable->getHardwareById($paramHardwareId, 1);
					$s = "var markers =[";
					$s .= "{";
					$s .= "'hardwarename':'" . $dataHardwareById->hardwarename . "',";
					$s .= "'address':'" . $dataHardwareById->address . "',";
					$s .= "'buyer':'" . $dataHardwareById->buyer . "',";
					$s .= "'created_date':'" . date(DATETIMEFORMAT, $dataHardwareById->created_date) . "',";
					$s .= "'updated_date':'" . ($dataHardwareById->updated_date > 0 ? date(DATETIMEFORMAT, $dataHardwareById->updated_date) : '0') . "'";
					$s .= "},";
					$s .= "];";
				} else {
					$s = "var markers ='';";
			}
			$this->view->assign("s", $s);
			$this->view->assign("itemid", $paramItemId);
			$this->view->assign("shipmentid", $paramShipmentId);
		}

		public function quickAddNewPresetAction()
		{
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$handle = $this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$defaultOvisNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::OVIS_SHEPHERD_SYSTEM . $handle);
			$instanceId = $defaultOvisNamespace->dbShepherd;
			if(Sss_Ultility_Common::in_array_field(Sss_Ultility_CommonViewParamater::PER_GRAPHS, Sss_Ultility_CommonViewParamater::ALL, 'feature', 'action' ,$this->listRole(), true) != 1 ) {
				$this->_redirect("/$handle/user/login");
			}
			$getParams = $this->_request->getParams();
			$presetGraphTable = new Shepherd_Model_Mapper_PresetGraph();
			$presetChartTable = new Shepherd_Model_Mapper_PresetChart();
			$presetChartContructor = new Shepherd_Model_PresetChart();
			$presetTable      = new Shepherd_Model_Mapper_Preset();
			$presetContructor = new Shepherd_Model_Preset();
			$chartTable      = new Shepherd_Model_Mapper_Chart();
			$chartContructor = new Shepherd_Model_Chart();
			$queryString     = isset($getParams['chart']) ? $getParams['chart'] : '';
			$arrChartList    = array();
			if ($queryString != '')
				$arrChartList = explode(',', $queryString);
			$queryString     = count($arrChartList) > 0 ? "?".'chart' . '=' . implode(',', $arrChartList).'&' : '';
			$sensor    = $getParams[Sss_Ultility_CommonViewParamater::SENSORT_ID];
			$vt        = $getParams[Sss_Ultility_CommonViewParamater::VALUE_ID];
			$color     = $getParams[Sss_Ultility_CommonViewParamater::COLOR_LIST];
			$graphName     = $getParams[Sss_Ultility_CommonViewParamater::GRAPH_NAME_LIST];
			$arrSensors = explode(',', $sensor);
			$arrVt = explode(',', $vt);
			$arrColors = explode(',', $color);
			$arrGraphNames = explode(',', $graphName);
			$end = strtotime(date(DATETIME_MYSQL_FORMAT));
			$start = $end - 24*60*60;
			$createBy   = $userInformation->accountid;
			$presetContructor->setPresetName(Resources::_('DEFAULT_PRESET_NAME'));
			$presetContructor->setCreatedBy($createBy);
			$presetContructor->setUpdatedBy($createBy);
			$presetContructor->setCreatedDate($start);
			$presetContructor->setUpdatedDate($end);
			$insertPresetId   = $presetTable->save($presetContructor,$instanceId);
			if (isset($insertPresetId) && (int) $insertPresetId > 0) {
				$presetUpdate = $presetTable->findById($insertPresetId,$instanceId);
				$presetUpdate->setPresetName(Resources::_('DEFAULT_PRESET_NAME').''.sprintf('%03d',$insertPresetId));
				$presetTable->save($presetUpdate,$instanceId);
			}
			$presetChartContructor->setChartName(Resources::_('DEFAULT_CHART_NAME'));
			$presetChartContructor->setFromDatetime($start);
			$presetChartContructor->setToDatetime($end);
			$presetChartContructor->setPreset($insertPresetId);
			$insertPresetChartId   = $presetChartTable->save($presetChartContructor,$instanceId);
			try {
				if (isset($insertPresetChartId) && (int) $insertPresetChartId > 0) {
					$presetChartUpdate = $presetChartTable->findById($insertPresetChartId,$instanceId);
					$presetChartUpdate->setChartName(Resources::_('DEFAULT_CHART_NAME') . ' ' . sprintf('%03d', $insertPresetChartId)); 
					$presetChartTable->save($presetChartUpdate,$instanceId);
					$timeRangeTypeValue = 3;
					$end = strtotime(date(DATETIME_MYSQL_FORMAT));
					$start = $end - 24*60*60;
					$chartContructor->setChartName(Resources::_('DEFAULT_CHART_NAME'));
					$chartContructor->setFromDatetime((int)$start);
					$chartContructor->setToDatetime((int)$end);
					$chartContructor->setFromValue(0);
					$chartContructor->setToValue(0);
					$chartContructor->setCreatedDate(time());
					$chartContructor->setUpdatedDate(time());
					$chartContructor->setCreatedBy($userInformation->accountid);
					$chartContructor->setUpdatedBy($userInformation->accountid);
					$chartContructor->setHardware($arrSensors[0]);
					$chartContructor->setTimeRangeType($timeRangeTypeValue);
					$chartContructor->setPresetChartId($insertPresetChartId);
					$chartContructor->setAverageValue(0);
					$chartContructor->setFilterValue(0);
					$chartContructor->setSmoothingValue(0);
					$insertChartId   = $chartTable->save($chartContructor,$instanceId);//Insert tables charts when click Make new preset
					if (isset($insertChartId) && (int) $insertChartId > 0) {
						$chartUpdate = $chartTable->findById($insertChartId,$instanceId);
						$chartUpdate->setChartName(Resources::_('DEFAULT_CHART_NAME') . ' ' . sprintf('%03d', $insertChartId));
						$chartTable->save($chartUpdate,$instanceId);
					}//End insert
					$arrChartList[] = $insertChartId;
					$queryString = count($arrChartList) > 0 ? "?".'chart'. '=' . implode(',', $arrChartList) : '';
					foreach ($arrSensors as $i=>$sensor) {
						$presetGraphContructor = new Shepherd_Model_PresetGraph();
						$presetGraphContructor->setPresetChart($insertPresetChartId);
						$presetGraphContructor->setColor('#' . $arrColors[$i]);
						$presetGraphContructor->setHardware($sensor);
						$presetGraphContructor->setGraphName($arrGraphNames[$i]);
						$presetGraphContructor->setValuetype($arrVt[$i]);
						$presetGraphTable->save($presetGraphContructor,$instanceId);
					}
					echo $insertChartId;
				}
			} catch (Exception $e) {
					Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
			}
			die;
		}
	}